While Loops

Basics

One of the most powerful aspects of computer programs is their ability to perform repetion, which is the ability to do something many times. The simplest form of repetition is the while loop, which does something as long as some condition is true.

For example, here is a small program that prints out the numbers 3, 2, and 1 using a while loop.

In [1]:
num_moons = 3
while num_moons > 0:
    print num_moons
    num_moons = num_moons - 1
3
2
1

The loop opens with the keyword while, followed by the loop’s controlling test. Since this test is true, i.e., num_moons is greater than 0 to start, Python executes the statements in the loop body, which is the set of indented statements under the loop control. This prints out 3 and subtracts 1 from num_moons. Python then re-checks the condition. It’s still true so the program prints ’2′ and subtracts 1 from num_moons again. Another check, another print statement: the program prints ’1′, then decrements num_moons again. Since the loop’s controlling condition is now false, the program is done.

We can see that this is the case by looking at the current value of num_moons.

In [2]:
num_moons
Out[2]:
0

While loops don't always execute

A while loop may execute any number of times, including zero. If instead of starting at 3, num_moons starts at -3, the loop condition is false the first time it is tested and the loop body doesn't execute at all.

In [3]:
print 'start'
num_moons = -3
while num_moons > 0:
    print num_moons
    num_moons = num_moons - 1
print 'end'
start
end

We can see that the code has been run, because it prints out the words 'start' and 'end', but nothing else is printed because the loop did not execute. It is important to keep this “zero pass” condition in mind when designing and testing code.

Infinite loops

A while loop may also execute indefinitely. Here’s another copy of the program that doesn’t subtract 1 from num_moons inside the loop body.

In [ ]:
print 'start'
num_moons = 3
while num_moons > 0:
    print num_moons
print 'end'

If we executed this program (not recommended) it would first the word 'start', then it would print out the number 3, then another 3, and it would keep printing 3's until it was interupted. Since the loop’s control condition was true when the loop started, and nothing happens inside the loop to change it, the loop will run until the user gets bored enough to halt it. This is usually not the desired behavior, but there are cases where an apparently infinite loop can be useful.

Video presentation

The first half of this video covers while loops using the examples above.