Computer Science 15-110, Spring 2011
Class Notes:  Loops


  1. "for" loops
    1. "for" loop over a range
      1. Range from 0 to y:  use range(y+1)
      2. Range from x to y:  use range(x, y+1)
      3. Range from x to y with step z:  use range(x, y+1, z)
      4. Range in reverse (use a negative step)
    2. "for" loop over a String
      1. With an index
      2. Without an index
  2. "while" loops
    1. Basic Syntax and Use
    2. Read Until a Sentinel
    3. Read Until a Condition
    4. Incorrect Usage:  Iterate Over a Range of Integers
  3. Nested loops

Loops

  1. "for" loops

    1. "for" loop over a range

      1. Range from 0 to y:  use range(y+1)

        # print the numbers from 0 to 4 (not 5)
        for x in range(5):
            print x


      2. Range from x to y:  use range(x, y+1)

        # print the numbers from 10 to 14 (not 15)
        for x in range(10, 15):
            print x


      3. Range from x to y with step z:  use range(x, y+1, z)

        # print the even numbers from 10 to 14 (not 15)
        for x in range(10, 15, 2):
            print x


      4. Range in reverse (use a negative step):

        # print the even numbers from 14 to 10 (not 9)
        for x in range(14, 9, -2):
            print x


    2. "for" loop over a String

      1. With an index

        # print each character in a String
        s = "Amazing!"
        for i in range(len(s)):
          print s[i]

      2. Without an index

        # print each character in a String
        for ch in "Wow!":
            print ch


  2. "while" loops

    1. Basic Syntax and Use

      while (test):
          body

      For example:

      def beHappy():
          happy = False
          while (not happy):
              response = raw_input("Are you happy yet? [yes or no] ")
              happy = (response == "yes")
          print "Well, now I'm happy, too!"

      Another example:

      def sumOfDigits(n):
          sum = 0
          n = abs(n)
          while (n != 0):
              sum += (n % 10)
              n /= 10
          return sum


    2. 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!"


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


    4. Incorrect Usage:  Iterate Over a Range of Integers

      # sum numbers from 1 to 10
      # note: you should use a "for" loop here, not a "while" loop
      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:


      # 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. Nested loops

    n = int(raw_input("How many rows? "))
    for row in range(n):
        for col in range(n):
            print "*",
        print


    Another example:

    n = int(raw_input("How many rows? "))
    for row in range(n):
        for col in range(row+1):
            print "*",
        print


    Again, with a useful helper function:

    def printStars(starCount):
        for col in range(starCount):
            print "*",
        print

    n = int(raw_input("How many rows? "))
    for row in range(n):
        printStars(row+1)



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