CPSC120A
Fundamentals of Computer Science I

Review 2

A practice test to review for the second test.

  1. Explain why functions are useful.

  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. spam = 1
      for i in range(5):
          spam = spam / i
      print(spam)
    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 sum_range(start, end, step), which takes as input integers start, end and step. Your function should return the sum of all of the values in the specified range.

  4. 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.