Lecture 9 — While Loops


  • Review the basic idea for loops
  • Construct loops using logical conditions: while loops
  • Use of loops for controlling information in lists
  • Single and multiple loops

Reading: Practical Programming, rest of Chapter 7.

Part 1: The Basics

  • Loops allow you to repeat a piece of code multiple times for many sophisticated programming tasks
  • We will see two ways to write loops: using while loops and for loops
  • while loops are more general: you can always write a for loop using a while loop. The reverse is not true: for loops allow for some shortcuts and are provided for convenience only.
  • We will start with while loops first and then see how we can simplify common tasks with for loops later.

Basics of While

  • Our first while loop just counts numbers from 1 to 10, and print them.

    while i<10:
        print i
        i += 1   ## if you forget this, your program will never end
  • General form of a while loop:

    while condition:
  • Steps

    1. Evaluate any code before while
    2. Evaluate the while loop’s condition:
      1. If it is True, evaluate the block of code, and then repeat the evaluation of the condition.
      2. If it is False, end the loop, and continue with the code after the loop.

    In other words, the cycle of evaluating the condition followed by evaluating the block of code continues until the condition evaluates to False.

  • Make sure your loop will always terminate.

Using Loops with Lists

  • Often, we use loops to repeat a specific operation on every element of a list.

  • We must be careful to create a number that will serve as the index of elements of a list. Valid values are: 0 up to (not including) the length of list.

    co2_levels = [ (2001, 320.03), (2003, 322.16), (2004, 328.07),\
                   (2006, 323.91), (2008, 341.47), (2009, 348.92),\
                   (2010, 357.29), (2011, 363.77), (2012, 361.51),\
                   (2013, 382.47) ]
    while i< len(co2_levels):
        print "Year", co2_levels[i][0], \
              "Co2 levels:", co2_levels[i][1]
        i += 1
  • Let’s make some errors to see what happens to the loop.

Part 1 Exercises

  1. Write a while loop to count down from 10 to 1.

  2. Use your loop to print the values in the above list in reverse order.

  3. Write a program to convert a string containing multiple numbers (like mystr below) to a list of integers (like mylist below).

    mystr = '1,2,4,4,5'
    mylist = [1,2,4,4,5]

Accumulation of values

  • Often, we use loops to accumulate some type of information such as adding all the values in a list.

  • Let’s change the loop to add numbers from 1 to 10.

    sum = 0
    while i<10:
        sum += i
        i += 1
    print sum
  • Let’s use a loop to add the numbers in a list.

    • Now, we will use the numbers the loop generates to index a list.
    • So, the loop must generate numbers from 0 to length of the list.
    co2_levels = [ (2001, 320.03), (2003, 322.16), (2004, 328.07),\
                   (2006, 323.91), (2008, 341.47), (2009, 348.92),\
                   (2010, 357.29), (2011, 363.77), (2012, 361.51),\
                   (2013, 382.47) ]
    while i< len(co2_levels):
        sum += co2_levels[i][1]
        i += 1
    print "Total co2_levels is", sum
  • Let’s have a more interesting example. Be very careful not to use an incorrect index for the list.

    • Count the number of values greater than 350.
    • Find the percentage change in each measurement year from the previous measurement year.
    • Find the years in which the Co2 levels fell down compare to the previous measurement.

Part 2 Exercises

  1. Suppose we wanted to print the first, third, fifth, etc. elements in a list. Write code to accomplish this.

  2. Now, use a similar loop code to print a little Christmas tree.

  3. Try this later: change your loop to work for any size Christmas tree.

Loops that end on other conditions

  • Here is a while loop to add the non-zero numbers that the user types in.

    sum = 0
    end_found = False
    while not end_found:
        x = int( raw_input("Enter an integer to add (0 to end) ==> "))
        if x == 0:
            end_found = True
            sum += x
    print sum
  • We will work through this loop by hand in class.

Multiple nested loops

  • As we can nest if statements, we can also nest loops.

  • Write a loop that compares every element in a list to every other element.

  • First naive solution:

    L = [2, 21, 12, 8, 5, 31]
    i = 0
    while i < len(L):
        j = 0
        while j < len(L):
            print L[i], L[j]
            j += 1
        i += 1
  • This solution counts looks at the same pair of indices twice: index 1,2 and 2,1 are both counted. This is not necessary.

  • How can we modify it so that we only visit each pair once?

  • Let’s use this loop to find the two closest values in the list.


  • Loops are especially useful for iterating over lists, accessing its contents, adding and counting values from lists.
  • Each loop has a stopping condition. The loop will end when the stopping condition is reached.
  • If the stopping condition is never reached, loops may become “infinite”. Your program in this case never ends.
  • A very common use of loops is the use of a counter, that starts at a specific position, and is incremented or decremented at each iteration. The stopping condition is often the counter reaching a specific value.
  • We will a simple way to write these common loops with a for loop in the next lecture.