Computer Science 15-110, Fall 2010
Class Notes:  Getting Started with while Loops


  1. The "while" statement
  2. Examples
    1. Read Until a Sentinel
    2. Read Until a Condition
    3. Find the Nth Positive Integer with Some Property
    4. Misuse:  Iterate Over a Range of Integers
  3. Practice Tracing
  4. Practice Mystery Methods
  5. Practice Problems

Getting Started with while Loops

  1. The "while" statement

    while (test):
        body

    For example:

    def powersOfTwo(upperLimit):
        n = 1
        while (n < upperLimit):
            print n
            n *= 2
        print "After loop, n = ", n

    And a similar example:

    def dividingByTwo(n):
        count = 0
        while (n > 0):
            print n
            n /= 2
            count += 1
        print "After loop, n=", n, " and count=", count

    And a different example:

    def functionsRace(finishLine):
        print "Functions race!"
        print "Function 1: y1 = 10 * x + 50"
        print "Function 2: y2 = x * x - 100"
        print "x\ty1\ty2"
        x = 0
        y1 = 0
        y2 = 0
        # while loop with conjunct condition
        while (y1 < finishLine and y2 < finishLine):
            y1 = 10 * x + 50
            y2 = x * x - 100
            print "%d\t%d\t%d" % (x, y1, y2)
            x += 1
        if (y1 > y2):
            print "Function 1 wins!"
        elif (y1 < y2):
            print "Function 2 wins!"
        else:
            print "It's a tie!"


  2. Examples
    1. Read Until a Sentinel

      # Keep reading names until the user enters "done"
      count = 0
      sentinel = "done"
      input = None
      print "Keep entering names.  To quit, enter", sentinel
      while (input != sentinel):
          input = raw_input("Enter name #" + str(count+1) + ": ")
          if (input != sentinel):
              count += 1
      print "You entered", count, "names!"

    2. Read Until a Condition

      # keep reading numbers until their sum exceeds 10
      sum = 0.0
      while (sum < 10):
          print "Sum = " + str(sum) + ". ",
          input = float(raw_input("Next number --> "))
          sum += input
      print "Final sum = ", sum

    3. Find the Nth Positive Integer with Some Property

      # find the nth number that is a multiple of both 4 and 7

      def isMultipleOf4Or7(x):
          return ((x % 4) == 0) or ((x % 7) == 0)

      def nthMultipleOf4Or7(n):
          found = 0
          guess = -1
          while (found <= n):
              guess += 1
              if (isMultipleOf4Or7(guess)):
                  found += 1
          return guess

      input = None
      while (input != -1):
          input = int(raw_input("Enter a # (or -1 to quit): "))
          if (input != -1):
              print "   nthMultipleOf4Or7(", input, ") =", nthMultipleOf4Or7(input)
      print "Bye!"

    4. Misuse:  Iterate Over a Range of Integers

      # sum numbers from 1 to 10
      # note:  this works, but you should not use "while" here.
      #        instead, do this with "for" (once you know how)
      sum = 0
      counter = 1
      while (counter <= 10):
          sum += counter
          counter += 1
      print "The sum from 1 to 10 is", sum

      Once again, but with a bug!:

      # sum numbers from 1 to 10
      # warning: buggy version!
      sum = 0
      counter = 0
      while (counter <= 10):
          counter += 1
          sum += counter
      print "The sum from 1 to 10 is", sum


      And once more, using a "for" loop (which we'll soon learn about):


      # sum numbers from 1 to 10
      sum = 0
      for counter in range(1,11):
          sum += counter
      print "The sum from 1 to 10 is", sum

  3. Practice Tracing

    1. # trace this code by hand, then run it to confirm your prediction
      x = 13
      y = 1
      while (y < x):
          print x,y
          x -= 2
          y += 3
      print x,y


    2. # trace this code by hand, then run it to confirm your prediction
      s = "abcde"
      while (len(s) < 15):
          print s
          s += "-" + str(len(s))
      print "Done, and s =",s


  4. Practice Mystery Methods

    1. # State what this function does, in just a few words of plain English.
      # Do not state line-by-line what it does at a low level.  Find the general pattern.
      # Also note that there is a clearer, faster, better way to do the same thing!

      def mysteryA(x, y):
          # assume x and y are non-negative integers
          c = 0
          while (x > 0):
              c += y
              x -= 1
          return c


    2. # State what this function does, in just a few words of plain English.
      # Do not state line-by-line what it does at a low level.  Find the general pattern.
      # Also note that there is a clearer, faster, better way to do the same thing!

      def mysteryB():
          c = 0
          input = "!"  # why do this?
          s = ""
          while (s.find(str(input)) < 0):
              s += str(input)
              c += 1
              input = "-" + raw_input("Enter an integer: ") + "-"
          return c

  5. Practice Problems
    In recitation...

    carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem