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(1, n, 2):
        print b
    
  4. For the following loops, indicate what will be printed.
    1. First piece of code:
      for x in range(4):
         for y in range(2, 4):
             print x , y
      

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