2016 September 14,

CS 111: while Loops

We've already learned for loops. Now we're going to learn a second kind of loop. First look at this code, and try to guess what it does. Then run it.

i = 1
while i < 5:
    print("Repetition is repetitive.")
    i = i + 1

You should think of a while as a repeated if. If the while statement (i < 5) is true, then the indented block gets executed. If the condition is still true, the indented block gets executed again. This repeats until the condition is no longer true. The variable i is called a loop counter. On the first pass through the loop, i has value 1. At the end of the first pass, its value is changed to 2. On the second pass through the loop, its value is 2. At the end of the second pass, its value is changed to 3. And so on.

Loop counters don't have to count up by 1 on each pass through the loop; they can count down by 1, or down by 5, or whatever you want. And usually they are used somewhere within the body of the loop. Here's a more sophisticated example:

sum = 0
n = 100
while n >= 0:
    sum = sum + n
    n = n - 2
print(sum)

Question 10A: Describe, in plain English, what that loop accomplishes.

Question 10B: Write a while loop to compute the sum 12 + 22 + 32 + ... + 1002. Also write a for loop to accomplish the same task.

You can nest while statements within while statements, and within if statements, and vice-versa, to your heart's content. This code prints out the auto insurance rates for all ages 16-34. Examine carefully, how the nesting works.

age = 16
while age <= 34:
    if age < 18:
        rate = 450
    elif age > 90:
        rate = 500
    elif age < 25:
        rate = 400
    else:
        rate = 300
    print(age, ":", rate)
    age = age + 1

Question 10C: Rewrite that code to use a for loop instead of a while loop.