Sub topic 4
Infinite loops and while True
This chapter covers loops that never end, and loops that are written to run until something inside them says stop. It assumes you can write a basic while loop and know how Python evaluates its condition. It also assumes you know that the loop body has to change something the condition depends on. You should be comfortable with if statements, comparison operators, and print and input.
Two kinds of infinite loop
An infinite loop is a while loop whose condition never becomes false. Python does not detect this. It runs the body again and again until you interrupt it, the program crashes, or the machine runs out of something such as memory.
Not every infinite loop is a mistake. There are two cases:
- Accidental. You meant the loop to end, but nothing in the body moves it toward ending. This is a bug.
- Intentional. The loop is written to run until an event happens, and you do not know in advance how many passes that takes. Examples are waiting for correct input, serving requests, or draining a queue.
The same mechanism produces both. The difference is whether you designed a way out.
Accidental infinite loops
The usual cause is that the variable in the condition never changes. Here is a loop that would run forever:
n = 3
while n > 0:
print(n)
# Bug: n is never decreased, so n > 0 is always true.Running it prints 3 until you stop it. A guarded version shows the same bug without hanging your terminal:
n = 3
passes = 0
while n > 0 and passes < 5:
print(n)
passes += 1 # safety guard, not part of the real logic
print("Stopped by the guard after", passes, "passes")A passes counter like this is a handy debugging tool. Add it temporarily when you suspect a loop is not terminating, then remove it once you have fixed the cause.
A condition that can never become false
Sometimes the variable does change, but in a way that cannot satisfy the exit test. Floating-point numbers are the common example, because most decimal fractions are stored approximately:
x = 0.0
steps = 0
while x != 1.0 and steps < 15:
x += 0.1
steps += 1
print(steps, x)Ten additions of 0.1 do not give exactly 1.0. The running total goes from slightly below 1.0 to slightly above it without ever equaling it. Without the steps < 15 guard, the loop would run forever. The loop stops at 15 passes with x near 1.5.
Two fixes work:
- Test with an inequality (
x < 1.0) instead of!=. Be aware that the last pass may still be off by one because of rounding. - Count with an integer and compute the float from it, for example
x = i / 10.
More generally, prefer <, <=, > and >= over == and != when the value changes by steps.
Other common causes
The following patterns also produce loops that never end:
- The update sits inside an
ifbranch that is never reached. - The update changes a different variable than the one the condition reads. A misspelled name or a variable assigned inside a function does this.
- The loop steps in the wrong direction, such as
n += 1in a loop that waits fornto fall below some limit. - A
continueskips the update. The pitfalls chapter covers this in detail.
Intentional infinite loops with while True
When you cannot state the stopping rule as a single condition at the top, write a loop that never ends by its own condition. Then leave from inside:
attempts = 0
while True:
answer = input("Password: ")
attempts += 1
if answer == "secret" or attempts == 3:
break
print("Done after", attempts, "attempt(s)")True is a constant, so the condition can never be false. The only way out is the break statement, which ends the nearest enclosing loop immediately. The next chapter covers break in full. Here you only need to know that it jumps to the first statement after the loop.
Why not put the exit test in the loop header? In the example above, the test depends on a value that the body creates (answer). To write while answer != "secret" and attempts < 3:, you would need to set answer to some dummy value before the loop. That pre-loop setup duplicates the logic and can be wrong. while True lets you read the input, then decide.
> Note on while 1: in Python 3, while 1: behaves the same as while True:. True is the more readable choice.
The control flow
This diagram shows where the exit sits. The condition check always passes, so leaving depends entirely on the test inside the body.
Patterns for exiting a while True loop
A while True loop needs at least one reachable way out. There are several.
Exit on a sentinel or empty source
Draining a queue is a case where the number of passes is not known ahead of time:
from collections import deque
tasks = deque(["email", "backup", "report"])
while True:
if not tasks:
break
task = tasks.popleft()
print("Running", task)
print("All tasks done")Here not tasks uses truthiness: an empty deque is falsy. You could also write while tasks:, which is simpler. Use while True when the loop does more than one kind of check, or when new tasks may arrive during the loop and you want the exit test to sit at a particular point in the body.
Exit with a retry limit
Retrying an unreliable operation needs two exits: success, and giving up. A single header condition would mix the two. With while True, each exit is its own if:
import random
random.seed(1)
attempt = 0
while True:
attempt += 1
succeeded = random.random() < 0.3
if succeeded:
print("Succeeded on attempt", attempt)
break
if attempt == 5:
print("Giving up after", attempt, "attempts")
breakSeeding the random generator makes the run repeatable while you experiment. Remove the seed in real code.
Exit with return, raise, or sys.exit
break is not the only way out. Inside a function, return ends the loop and the function together. An uncaught exception also ends it, and so does sys.exit(). For example:
def ask_age():
while True:
text = input("Age: ")
if text.isdigit():
return int(text)
print("Please type digits only.")This function can only return a valid number. The loop has no break because return is the exit.
Exit on Ctrl+C
A program that is meant to run until a person stops it, such as a monitor or a simple server, can catch the keyboard interrupt:
import time
count = 0
try:
while True:
count += 1
print("Heartbeat", count)
time.sleep(1)
except KeyboardInterrupt:
print("\nStopped by user after", count, "heartbeats")Pressing Ctrl+C raises KeyboardInterrupt inside the loop. The try block sits outside the loop, so the exception leaves it. Put the try outside the loop. If you put it inside, the handler would catch the interrupt on every pass and the loop would continue.
Stopping a runaway loop
If a script is stuck, you can usually stop it as follows.
| Situation | What to do |
|---|---|
| Script running in a terminal | Press Ctrl+C. Python raises `KeyboardInterrupt` and prints a traceback showing the line it was on. |
| Script blocked in `input()` | Press Ctrl+C, or Ctrl+D (Ctrl+Z then Enter on Windows) to signal end of input. |
| Ctrl+C has no effect | Close the terminal, or kill the process from another terminal with your operating system's tools. |
| Interactive environment such as a notebook | Use its interrupt or restart-kernel button. |
The traceback printed after Ctrl+C is useful. It shows exactly which line was running when you interrupted, which tells you which loop is stuck.
Making a while True loop safe
A while True loop is easy to get wrong because the exit is not visible in the header. A few habits keep it under control:
- Know your exit before you write the loop. Write down which event ends it. If you cannot name one, reconsider the design.
- Make the exit reachable. Check that at least one path through the body reaches
break,return, or araise. - Prefer one exit, or a few clearly separate ones. Each
breakis a place a reader must look. Comment the reason when there are several. - Put a bound on anything that can fail repeatedly. A retry loop with no attempt limit can run forever if the failure is permanent.
- Keep updates ahead of any early jump. If you add
continue, make sure the loop's progress does not depend on lines after it. - Do not swallow the exit signal. A bare
except:inside the loop catchesKeyboardInterruptand makes Ctrl+C stop working. Catch specific exceptions such asValueError.
Choosing between a header condition and while True
Both forms can express the same loop. Choose by where the stopping rule is easiest to read.
| Use a header condition when | Use `while True` when |
|---|---|
| One simple test describes when to continue | The test needs a value produced inside the body |
| The state is set up before the loop | There are several different reasons to stop |
| You want readers to see the rule at a glance | The exit sits in the middle of the body, not at the top |
For example, while n > 0: is clearer than while True: followed by if n <= 0: break as the first line. Do not use while True just to avoid initializing a variable if a header condition reads naturally.
Recap
- Python does not detect infinite loops. You must make sure the loop makes progress or has a reachable exit.
- Accidental infinite loops come from state that never changes, changes the wrong way, or can never match an exact test (especially with floats).
while Trueis a deliberate infinite loop. The exit is abreak,return, an exception, or a program exit inside the body.- A temporary pass counter helps you debug a loop that will not stop.
- Ctrl+C raises
KeyboardInterrupt, and a bareexcept:inside the loop can hide it.
Exercise
This loop is meant to print 10, 8, 6, 4, 2 and then stop, but it runs forever. Explain why, and fix it. n = 10 while n != 0: print(n) n -= 3
Show answer
The value of n goes 10, 7, 4, 1, -2, -5 and so on. It steps over 0 and never equals it, so n != 0 is always true. Two fixes are possible. To get the requested output, subtract 2 instead of 3 (n -= 2), so n reaches 0 exactly. Changing the test to n > 0 also makes the loop end when n drops to 1 or below, whatever the step. Using an inequality is the safer habit.
Exercise
Write a loop using while True that asks the user for a number with input(), prints its square, and stops when the user types the word quit. What does the loop do if the user types something that is neither a number nor quit?
Show answer
One solution: while True: text = input("Number (or quit): ") if text == "quit": break print(int(text) ** 2) If the user types something such as "abc", int(text) raises ValueError and the program crashes with a traceback. To handle it, wrap the conversion in try and except ValueError, print a message, and let the loop continue. Catch ValueError specifically, not a bare except, so Ctrl+C still works.
Exercise
A retry loop is written as while True: and calls a function that always fails. It has an if success: break test but no attempt limit. What happens, and how do you fix it?
Show answer
The loop never ends, because the only exit is success and success never occurs. Fix it by counting attempts and adding a second exit, for example attempt += 1 followed by if attempt == 5: break (or raise an error after the loop). Every loop that retries something that can fail permanently needs a bound like this.