This page is going into a bit of detail about while loops. We will cover:
while loops that do nothing
Infinite loops—something you should avoid
The break statement and infinite loops
Subsection5.4.1while Loops That Do Nothing
Take another look at the flowchart for a while loop:
If the condition is False when you enter the loop, the loop body will never be executed at all. The loop will “do nothing”. Here’s another way of doing the “loop until you get good input”:
Let’s say you enter a number like 45. The condition years <= 0 evaluates to False, and the body of the loop is never executed.
Note5.4.2.
The disadvantage of this sort of loop is the duplication of the input calls. One advantage of this loop is that the prompt for an error can be different than the initial prompt.
You should be aware that while loops have the ability to “do nothing”, and sometimes do it quite gracefully, making your code more elegant.
Subsection5.4.2Infinite Loops
An endless source of amusement for programmers is the observation that the directions on shampoo, “Lather, rinse, repeat,” are an infinite loop because there is no iteration variable telling you how many times to execute the loop.
In some loops, like the table of squares and cubes from Section 5.2, we can prove that the loop terminates because we know that the value of n is finite, and we can see that the value of n gets larger each time through the loop, so eventually it will reach 6.
Other times, a loop is infinite because the value of a variable in the condition never changes, or the loop condition is always True.
Here is a loop that was supposed to print the numbers 1 to 10, but which will never end because the code is accidentally subtracting one instead of adding one. 1
As you can see above, the Code Lens gives you a warning because it runs for over 1000 steps. If you make the mistake of running this code in Thonny (see Section 1.6), you can stop a runaway Python program by clicking the stop sign icon. If you are using some other development environment, make sure you find out its way of stopping a program.
Subsection5.4.3The break Statement
Ordinarily, we exit a while loop when the condition becomes False. However, Python provides another way to exit from a loop. If Python encounters a break statement, it will immediately exit the loop.
Here’s an example. Suppose you want to take input from the user until they type done. You could write:
while True:
line = input('Word: ')
if line == 'done':
break
print(line)
print ('Goodbye!')
The loop condition is True, which can never be false. Ordinarily, the loop body would run forever. But when the if condition is True (when line == 'done'), the break will take us out of the loop.
Checkpoint5.4.3.
At what word will the while loop shown above terminate?
At each iteration, the loop body prompts the user with Word:. If the user types done, the break statement exits the loop. Otherwise, the program echoes whatever the user types and goes back to the top of the loop. Here’s a sample run:
Word: hello there
hello there
Word: finished
finished
Word: done
Goodbye!
This way of writing while loops is common because you can check the condition anywhere in the loop (not just at the top) and you can express the stop condition affirmatively (“stop when this happens”) rather than negatively (“keep going until that happens.”).
Warning5.4.4.Beware of break.
Although the while True:/break combination is in common use, many programmers consider it to be bad style. Using this sort of code requires programmers to read the entire loop body to find the exit condition rather than looking at the head of the loop.
This problem becomes worse if the loop body has several break statements, each giving a new place to leave the loop and another thing for the programmer to keep track of.
Use while True: with break only if there is absolutely no other way to achieve the effect you want.
Never usewhile True:withbreakas a substitute for carefully thinking through the condition for exiting awhileloop!
You will find that you can often use compound conditions (and and or) to avoid the need for break.
Checkpoint5.4.5.
Construct a block of code that prints the numbers 1 through 5. Make sure you use correct indentation! Also, there will be three code blocks that aren’t used in the final solution.
n = 0
---
while (n < 5):
---
while (n < 5) #distractor
---
while (n <= 5): #distractor
---
while (n > 5): #distractor
---
print(n + 1)
---
n = n + 1
To any experts reading this: Yeah, I know about integer overflow, but cut me a break here.