10: The While Loop

Introduction

This will be a short tutorial, as while loops are pretty easy. You MUST understand conditionals to continue. While loops rely on an expression to operate. As long as the expression is True, the loop will run. When the expression stops being True (ie. it is False), so does the loop.

WHILE loop structure

The basic structure of a while loop is as follows:

while (expression): 
    # Do something

This will execute the code inside the # Do something section AS LONG AS the expression evaluates to True. Let’s look at a basic example:

i = 0 

while i > 10: 
    print i 
    i = i + 1

What will this print? Does the code change if we change the order of the statements inside the loop like so?

i = 0 

while i > 10: 
    i = i + 1 
    print i

Another way to use a while loop is to utilize the power of if statements to control the flow of the loop. This is done using what is often called a flag. The flag is initially True, and is set to False upon some condition. Once it is False, the while loop stops.

i = 0 
flag = True 

while flag: 
    i = i + 1 
    print i 
    if i == 10: 
        flag = False

Check yourself to see how these results are similar.

Yet another way is to set the while loop’s expression to always be True. This would cause the loop to run forever! This is called an infinite loop. Fortunately, we can use the break statement to “break out” of the loop. The break statement basically forces the loop to stop if it is run.

i = 0 

while True: 
    i = i + 1 
    print i 
    if i == 10: 
        break

Any of the above methods are suitable for labs. Try to pick the best one based on the problem, and make sure you understand all of them for tests and exams.

Replacing FOR loops

for loops are similar to while loops, but can only operate at a finite length, and can’t easily rely on Boolean operations to control their flow.

As a rule, any for loop can be turned into a while loop. However, any while loop can not be turned into a for loop.

Try it yourself! Try to turn this FOR loop into a WHILE loop:

for i in range(100): 
    print "my number is ", i

Easy, right? Now, try to change this loop to a FOR loop.

from random import randint 
i = 0 

while i != 50: 
    i = randint(0, 100) #get random int from 0 to 100

Try this out! It’s not possible to change this loop into a FOR loop.