12. While Loops

../../_images/ferris_wheel.svg

A for loop is used when a program knows it needs to repeat a block of code for a certain number of times. A while loop is used when a program needs to loop until a particular condition occurs. Use a for loop when you know how many times to loop, use a while loop when you want to loop until something happens.

Oddly enough, a while loop can be used anywhere a for loop is used because OUR “condition” can be a count. That is, the while loop can loop until a variable reaches a certain value. If that’s the case, why have a for loop if a while loop can do everything?

Because the for loop is simpler to use and code. A for loop that looks like this:

Using a for loop to print the numbers 0 to 9
1for i in range(10):
2    print(i)

…can be done with a while loop that looks like this:

Using a while loop to print the numbers 0 to 9
1i = 0
2while i < 10:
3    print(i)
4    i = i + 1
../../_images/carousel.svg

Line 1 of the while loop sets up a “sentinel” variable that will be used to count the number of times the loop has been executed. This happens automatically in a for loop eliminating one line of code. Line 2 contains the actual while loop. The format of the while loop is very similar to the if statement. If the condition holds, the code in the loop will repeat. Line 4 adds to the increment value. In a for loop this happens automatically, eliminating another line of code. As one can see from the code, the for loop is more compact than a while loop and is easier to read. Otherwise programs would do everything with a while loop.

A common mistake is to confuse the for loop and the while loop. The code below shows a programmer that can’t quite make up his/her mind between a for loop or a while loop.

Example of a confused loop
1while range(10):
2    print(i)

Don’t use range with a while loop!

The range function only works with the for loop. Do not use it with the while loop!

12.1. Using Increment Operators

../../_images/roller-coaster.svg

Remember that back in Back in Increment/Decrement Operators we learned it is possible to short-hand the code:

i = i + 1

With the following:

i += 1

In the while loop it would look like:

1i = 0
2while i < 10:
3    print(i)
4    i += 1

This can be done with subtraction and multiplication as well. For example:

i *= 2

Is the same as:

i = i * 2

See if you can figure out what would this print:

i = 1
while i <= 2 ** 32:
    print(i)
    i *= 2

12.2. Common Problems With while Loops

The programmer wants to count down from 10. What is wrong and how can it be fixed?

1i = 10
2while i == 0:
3    print(i)
4    i -= 1

What is wrong with this loop that tries to count to 10? What will happen when it is run? How should it be fixed?

1i = 1
2while i < 10:
3    print(i)

12.3. Looping Until User Wants To Quit

A very common operation is to loop until the user performs a request to quit. Give this code example a try.

Looping until the user wants to quit
1quit = "n"
2while quit == "n":
3    quit = input("Do you want to quit? ")

It isn’t perfect. It will loop if the use types “no”, “N”, or “NO!”. She must type exactly “n”. Go back and review Text Comparisons if you want to make the match more flexible.

../../_images/dragon.svg

We can expand this pattern to use a Boolean done variable to trigger an exit from the loop.

Here’s an example where we can exit the game by quitting, or attacking the dragon:

Looping until the game is over or the user wants to quit
 1done = False
 2while not done:
 3    quit = input("Do you want to quit? ")
 4    if quit == "y":
 5        done = True
 6
 7    attack = input("Does your elf attack the dragon? ")
 8    if attack == "y":
 9        print("Bad choice, you died.")
10        done = True

This isn’t perfect though, because if the user says she wants to quit, the code will still ask if she wants to attack the dragon. How could you fix this? Take a look at this example.

Looping until the game is over or the user wants to quit
 1done = False
 2while not done:
 3    quit = input("Do you want to quit? ")
 4    if quit == "y":
 5        done = True
 6
 7    if not done:
 8        attack = input("Does your elf attack the dragon? ")
 9        if attack == "y":
10            print("Bad choice, you died.")
11            done = True
12
13    if not done:
14        attack = input("Does your elf attempt to steal the gold? ")
15        if attack == "y":
16            print("Bad choice, you died.")
17            done = True

12.4. The break And continue Statements

../../_images/stop.svg

If you are in the middle of a for or while loop, and your code encounters a break statement, you’ll immediately exit the loop.

 1while True: # Loop forever
 2    quit = input("Do you want to quit? ")
 3    if quit == "y":
 4        break
 5
 6    attack = input("Does your elf attack the dragon? ")
 7    if attack == "y":
 8        print("Bad choice, you died.")
 9        break
10
11    attack = input("Does your elf attempt to steal the gold? ")
12    if attack == "y":
13        print("Bad choice, you died.")
14        break

If you are in the middle of a loop, and your code encounters a continue statement, you’ll immediately be sent back up to the top of the loop.

12.5. Review

12.5.1. Review Questions

  1. Write a while loop that will run the same as the following code:

for i in range(10):
    print(i)
  1. What will this code print, and why?

i = 1
while i <= 2**32:
    print(i)
    i *= 2
  1. Write a simple loop that asks the user if they wants to keep looping. Loop until they says “no”.

  2. The programmer wants to count down from 10. What is wrong and how to fix it?

i = 10
while i == 0:
    print(i)
    i -= 1
  1. What is wrong with this loop that tries to count to 10? What will happen when it is run?

i = 1
while i < 10:
    print(i)

12.5.2. On-line Review Problems

Practice on-line by completing the while loop problems starting with 04 available here:

https://repl.it/community/classrooms/174286