3.5. while Loops
The for loop takes a collection of items and executes a block of code once for each item in the collection. In contrast, the while loop runs while a certain condition is true.
Basic of while loop
One simple example of a while loop is counting up a series of numbers. For example, the following while loop counts from 1 to 5.
Using a flag
A flag is a variable that determines whether or not the entire program is active. This could be use to stop the while statement: the program run while the flag is set to True and stop when any of the value of the flag(s) to False. Let's add a flag to this simple while loop:
Using break to Exit a Loop
The break statement can be used to stop for or while process. Here's an example:
Using continue in a Loop
Rather than breaking out of a loop entirely, we can use continue to return to the beginning of the loop based on the result of a conditional test. Let's see an example of printing odd numbers:
- First we set number_now to 0.
- Because it's less than 10, Python enters the while loop.
- Once inside the loop, we add number_now by += 1.
- The if statement then checks the modulo of number_now and 2.
- When the if statement is True, the continue will ignore the rest of the loop and return to the beginning.
- When number_now %2 == 0 is False, the next part is executed (print the number when number_now %2 == 0 is False).
Avoiding Infinite Loop
Every while loop needs a way to stop running, so it won't continue to run forever. For example, this counting loop should count from 1 to 10. However, if you accidentally make some mistakes (forgot to add +=1, for example) the loop will run forever. Try it.
To avoid writing infinite loops, test every while loop and make sure the loop stop when you expect it to stop. Make sure at least one part of the program can make the loop's condition False or cause it to reach a break statement.
Exercise 3.5
Pizza Toppings
Write a loop that ask the user:
Please enter your choice of pizza toppings:
until they enter a 'quit' value. As they enter each topping, print a message:
I will add {topping name} to their pizza.
Movie Tickets
A movie theater charges different ticket prices depending on a person's age. If a person is under the age of 3, the ticket is free; if they are between 3 and 12, the ticket is $10; and if they are over age 12, the ticket is $15. Write a loop in which you ask users their age, and then tell them the cost of their movie ticket.
Three Exits
Write different version of no.1 that satisfies at least one of the following:Use a conditional test in the while statement to stop the loop.
Use an active variable (a flag) to control how long the loop runs.
Use a break statement to exit the loop when the user enters a 'quit' value.