Computer Science 15-110, Fall 2010
Class Notes:  "for" Loops and Infinite 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. Without an index
      2. With an index
        1. the old-fashioned way
        2. the newfangled way (with enumerate)
  2. Nested loops
  3. Infinite "while" loop with break
  4. Practice Problems
    1. Sum the numbers from 1 to N
    2. Sum the odd numbers from 1 to N
      1. Using "if"
      2. Using a different increment
    3. Sum the first N odd numbers
    4. Reverse a String
    5. isPrime
    6. fasterIsPrime
    7. nthPrime

"for" Loops and Infinite 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. Without an index

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

      2. With an index

        1. the old-fashioned way

          # print every other character in a String
          s = "Amazing!"
          for i in range(len(s)):
              if (i % 2 == 0):
                  print s[i]

        2. the newfangled way (with enumerate)

          # print every other character in a String
          s = "Amazing!"
          for i, ch in enumerate(s):
              if (i % 2 == 0):
                  print ch

  2. Nested loops

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


  3. Infinite "while" loop with break

    while (True):
        response = raw_input("Enter a string (or 'done' to quit): ")
        if (response == "done"):
            break
        print "  You entered: ", response
    print "Bye!"

  4. Practice Problems

    1. Sum the numbers from 1 to N

      def sumFrom1ToN(n):
          sum = 0
          for i in range(n+1):
              sum += i
          return sum

      # let's see it in action...
      for n in range(-2,6):
          print n, sumFrom1ToN(n)

    2. Sum the odd numbers from 1 to N

      1. Using "if"

        def sumOddsFrom1ToN(n):
            sum = 0
            for i in range(n+1):
                if (i % 2 == 1):
                    sum += i
            return sum

        # let's see it in action...
        for n in range(-2,6):
            print n, sumOddsFrom1ToN(n)

      2. Using a different increment

        def sumOddsFrom1ToN(n):
            sum = 0
            for i in range(1, n+1, 2):
                sum += i
            return sum

        # let's see it in action...
        for n in range(-2,6):
            print n, sumOddsFrom1ToN(n)


    3. Sum the first N odd numbers

      def sumOfFirstNOdds(n):
          sum = 0
          for i in range(n):
              sum += 2*i+1
          return sum

      # let's see it in action...
      for n in range(6):
          print n, sumOfFirstNOdds(n)

      Or...

      def sumOfFirstNOdds(n):
          sum = 0
          for i in range(1,2*n+1,2):
              sum += i
          return sum

      Or...

      def sumOfFirstNOdds(n):
          sum = 0
          nextOdd = 1
          for i in range(n):
              sum += nextOdd
              nextOdd += 2
          return sum

      Once more, this time with a bug...

      def sumOfFirstNOdds(n):  # This version has a bug!
          sum = 0
          for i in range(n):
              sum += 2*n+1
          return sum

    4. Reverse a String

      def reverse(s):
          rev = ""
          for ch in s:
              rev = ch + rev
          return rev

      # let's see it in action...
      print reverse("abcdefg")
      print reverse("How do you know when it's time to tune your bagpipes?")

    5. isPrime

      #Note: there are faster/better ways.  We're just going for clarity and simplicity here.
      def isPrime(n):
          if (n < 2):
              return False
          for factor in range(2,n):
              if (n % factor == 0):
                  return False
          return True

      # And take it for a spin
      for n in range(500):
          if isPrime(n):
              print n,

    6. fasterIsPrime

      #Note: this is still not the fastest way, but it's a nice improvement.
      def fasterIsPrime(n):
          if (n < 2):
              return False
          if (n == 2):
              return True
          if (n % 2 == 0):
              return False
          maxFactor = int(round(n**0.5))
          for factor in range(2,maxFactor+1):
              if (n % factor == 0):
                  return False
          return True

      # Verify these are the same
      for n in range(1000):
          if (isPrime(n) != fasterIsPrime(n)): print n
          assert(isPrime(n) == fasterIsPrime(n))
      print "They seem to work the same!"

      # Now let's see if we really sped things up
      import time
      bigPrime = 499 # Try 1010809, or 10101023, or 102030407
      print "Timing isPrime(",bigPrime,")",
      time0 = time.time()
      print ", returns ", isPrime(bigPrime),
      time1 = time.time()
      print ", time = ",(time1-time0)*1000,"ms"

      print "Timing fasterIsPrime(",bigPrime,")",
      time0 = time.time()
      print ", returns ", fasterIsPrime(bigPrime),
      time1 = time.time()
      print ", time = ",(time1-time0)*1000,"ms"

    7. nthPrime

      def nthPrime(n):
          found = 0
          guess = 0
          while (found <= n):
              guess += 1
              if (isPrime(guess)):
                  found += 1
          return guess

      # and let's see a list of the primes
      for n in range(10):
          print n, nthPrime(n)


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