Sub topic 4
Infinite loops and while True
This chapter assumes you know variables, comparison and boolean operators, if statements with indentation, and basic use of print and input. You should also know the basic shape of a while loop.
What an infinite loop is
An infinite loop is a loop whose condition never becomes false and that nothing else stops. The program keeps repeating the body until you interrupt it (Ctrl+C in a terminal) or the process is killed.
Most infinite loops are bugs. The loop variable is never updated, or it is updated in the wrong direction:
n = 3
while n > 0:
print(n)
n += 1 # bug: n grows, so n > 0 is always trueSome infinite loops are intended. Programs that wait for events, such as servers, games and menus, run until something tells them to stop. Python has a standard way to write these.
Writing a deliberate loop with while True
The condition True is always true, so while True: never ends on its own. You supply the exit yourself with break, or with return inside a function.
attempts = 0
while True:
answer = input("Password: ")
attempts += 1
if answer == "secret" or attempts == 3:
break
print("Done after", attempts, "attempt(s)")Here the loop stops when the password is correct or when the third attempt is used. The number of passes is not known ahead of time, and the exit test needs a value read inside the body. Both facts make while True a good fit.
The alternative is to repeat the input call before the loop and again at the bottom, so the condition can use the value. That duplicates code. while True with one break keeps the read in a single place.
Rules for a safe while True loop
A while True loop needs a reachable exit. Check these points when you write one:
- At least one
breakorreturnmust be reachable on some path through the body. - The exit test must depend on something that changes during the loop, such as input, a counter or a result.
- Put a limit on the loop when failure is possible. In the password example,
attempts == 3guarantees the loop ends even if the user never types the right answer.
Without the third rule, a loop that waits for something that never happens will wait forever. For example, a loop that polls a service until it is ready should usually also stop after a maximum number of tries or a time limit.
Common causes of accidental infinite loops
The following mistakes produce loops that never end. They are covered further in a later chapter, but you should recognize them now.
| Cause | Example | Fix |
|---|---|---|
| Forgetting the update | `while n > 0:` with no change to `n` | Add `n -= 1` |
| Updating in the wrong direction | `n += 1` when the test is `n > 0` | Move `n` toward the exit |
| Update skipped by `continue` | `continue` placed before `i += 1` | Update before `continue` |
| Condition can never be false | `while x != 10:` when `x` jumps from 9 to 11 | Use `<` or `<=` |
| Float comparison | `while x != 1.0:` with `x += 0.1` | Use an inequality, or count with integers |
The last two rows share a pattern: an equality or inequality test (==, !=) can be stepped over. A range test (<, <=) is safer.
The continue case is worth seeing once:
i = 0
while i < 10:
if i % 2 == 0:
continue # bug: i is never incremented, so this loops forever
i += 1When i is 0, the if is true, continue jumps back to the condition, and i is still 0. Nothing in the loop can change that.
Stopping a runaway loop
If a program seems stuck, press Ctrl+C in the terminal. Python raises KeyboardInterrupt, and the traceback shows the line that was running. That line is usually inside the loop you need to fix.
When you are testing a loop you are unsure of, add a temporary guard:
count = 0
while True:
count += 1
if count > 1000:
print("Safety stop")
break
# ... the code under test ...Remove the guard once you are confident that the real exit works.
Summary of the working model
- A
whileloop ends only when its condition is false, or whenbreakorreturnruns. while Truemoves the exit decision from the condition into the body.- Every
while Trueneeds a reachable exit and, where failure is possible, a limit.
Exercise
The loop below is meant to read numbers until the user types 0, then print the total. It never stops, even when the user types 0. What is wrong, and how do you fix it? total = 0 / while True: / n = int(input()) / total += n / print(total)
Show answer
The body has no break, so nothing can end the loop and the print is never reached. Add an exit test after reading the number: if n == 0: break. Put that test before total += n, or leave it after, since adding 0 changes nothing. The loop then ends when the user types 0.
Exercise
Why is while x != 10 risky when x starts at 1 and the body does x += 3?
Show answer
The values of x are 1, 4, 7, 10, so here it happens to stop. If the step were 4 instead, x would go 1, 5, 9, 13 and never equal 10, so the loop would run forever. Use while x < 10, which ends once x passes 10.