CPSC120B
Fundamentals of Computer Science I

Review 2

A practice test to review for the second test.

  1. You can create any program you can imagine without creating any functions. So why is it useful to create functions?

  2. For each of the following snippets of Python code, give what would be printed to the command line if run. If the snippet will not print anything because of an error, just put error.

    1. eggs = 7
      
      if eggs > 0 and eggs < 5:
          print(eggs)
      if eggs < 7:
          print(eggs ** 2)
      else:
          print(eggs // 2)
            
    2. def spam(eggs):
          return eggs * eggs
      ham = spam(spam(2))
      print(ham)
    3. eggs = 0
      
      def spam(ham):
          eggs = ham
      
      spam(7)
      print(eggs)
    4. def spam(eggs, ham):
          eggs = ham
          return ham
      eggs = 2
      ham = eggs + 1
      spam(eggs, ham)
      print(eggs)
    5. def spam(eggs, ham):
          bacon = 0
          if (eggs > 0):
              if (ham  < 0):
      	    bacon = eggs + -1 * ham
          else:
              if ham > 0:
      	    bacon = -1 * eggs + ham
          return bacon
      
      print(spam(-1, -1))
      
    6. spam = 0
      for i in range(1, 5):
          spam = spam * i
      print(spam)
            
    7. def spam(eggs):
          ham = 0
          if eggs % 2 == 0:
              ham = eggs
          return ham
      
      accumulator = 0
      for i in range(10):
          accumulator += spam(i)
            
  3. Write a function called lazy_increase(n), which returns \(2 \times n\) if n is odd and divisible by 3. It should return \(1.5 \times n\) if n is odd and not divisible by 3. It should return \(n\) in all other cases.