Lecture 9 — While Loops

Overview

  • 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: in Python you can always write a for loop using a while loop.
  • 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.

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

    while condition:
        block
    
  • Steps

    1. Evaluate any code before while
    2. Evaluate the while loop’s condition:
      1. If it is True, then 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.

  • An important question that is sometimes easy to answer and sometimes very hard to answer is to 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) ]
    
    i=0
    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, printing the values of the loop counting variable i (it could be some other variable name as well).
  2. Modify your loop to print the values in the list co2_levels in reverse order.
  1. Write a program to convert a string containing multiple (like mystr below) to a list of integers (like mylist below).

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.

    i=1
    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, something that Python already does for use
    • 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) ]
    
    i=0
    sum=0
    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 CO2 values in the list that are greater than 350.
    • Calculate print the percentage change in each measurement year from the previous measurement year.
    • Determine the years in which the CO2 levels fell down compared to the previous measurement. Output just these years

Part 2 Exercises

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

    months=['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']
    
  2. Now, use a similar loop code to print a little evergreen tree.

        *
       ***
      *****
     *******
    *********
       ***
       ***
    
  3. Try this later: change your loop to work for any size 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
        else:
            sum += x
    
    print sum
    
  • We will work through this loop by hand in class.

Nested loops

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

  • Write a loop that prints every pairing of values in a list.

  • 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 pairs 1,2 and 2,1 are both shown.

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

  • More challenging: let’s use this loop to find the two closest values in the list.

Summary

  • Loops are especially useful for iterating over a list, 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.