CS 107: Pictures and Sounds: Programming with Multimedia

Kalamazoo College

Spring 2008

Problem Set on If Statements and For Loops


  1. For what possible values of x are statements A and B executed in the following two pieces of code?

    1. First piece of code:

      if (x >= 3):
          if (x == 7):
             statement A 
      
          else:
      	statement B 
      

    2. Second piece of code:

      if (x >= 3):
          if (x == 7):
             statement A 
      else:
         statement B 
      
      

  2. Explain the difference between the following two pieces of code. For each piece of code assume that the variables x and y have been defined and assigned a value before reaching this section.

    1. First piece of code:
      s = 0
      if ( x > 0 ):
          s = s + 1
      if ( y > 0 ):
          s = s + 1
      

    2. Second piece of code:
      s = 0
      if ( x > 0 ):
          s = s + 1
      elif ( y > 0 ):
          s = s + 1
      
  3. What does the following for statement do? Assume that n is some positive integer.
    for b in range(n, 0, -1):
        print b
    
  4. For the following loops, indicate what gets printed. (Note that str is a function that takes a number and returns the corresponding string. For example str(3) returns the string "3".)
    1. First piece of code:
      for x in range(4):
         for y in range(1, 4):
             print str(x) + ", " + str(y)
      

    2. Second piece of code:
      for x in range(4):
         for y in range(x, 4):
             print str(x) + ", " + str(y)