Q1What does this code print?n = 3
while n > 0:
print(n)
n -= 1
while Loops and Avoiding Infinite Loops
Pick up Python while loops, dodge infinite loops, and learn when to choose while over for — every example runs in your browser.
The previous for chapter focused on loops where the count or target is known up front.
The while statement covered here is a loop that repeats "as long as a condition holds", and it's used when the number of iterations isn't known in advance. Retry handling, queue draining, game loops — it shows up everywhere in real code.
while basics — repeat while the condition is True
while condition: runs the block repeatedly as long as the condition is True. Every time the loop spins, the condition is re-evaluated, and the moment it becomes False, the loop exits.
It's similar to for in shape, but instead of pulling from a target, it loops on the condition itself.
Condition → if True, run the body → check the condition again → exit when False. The cardinal rule of while: drive the condition toward False inside the body.
# The basic shape — print 0 through 4
count = 0
while count < 5:
print(count)
count += 1
# 0 / 1 / 2 / 3 / 4
# Drain remaining tasks from a queue
tasks = ["send mail", "backup", "deploy"]
while tasks:
task = tasks.pop(0) # take from the front
print(f"processing: {task}")
# processing: send mail / processing: backup / processing: deploy
The second example relies on the fact that while tasks: flips to False the moment the list is empty, using the truthiness rules from earlier (an empty list is False).
Avoiding infinite loops — always provide a termination condition
The biggest pitfall with while is the infinite loop. If you forget the update that flips the condition to False, the program never stops. Even in this in-browser console, that freezes the page until it times out a few seconds (or tens of seconds) later.
# Bad: n never changes inside the body, so it never ends
# n = 10
# while n > 0:
# print(n)
# (Don't run this — it freezes the browser / times out)
# Good: decrement n each time so the condition eventually becomes False
n = 10
while n > 0:
print(n)
n -= 1
Whenever you write a while, check that you can answer "how does the condition become False?"
Before you run it, point at the code and confirm that every variable in the condition is updated somewhere in the loop body.
Using break and continue inside while
The break / continue you saw with for work the same inside while.
Even while the condition is True, break decisively exits the loop and continue redoes the current iteration — these are the typical patterns.
# Simulating retries: up to 5 attempts, break when found
responses = [None, None, "OK", "OK", "OK"] # mock external API responses
attempt = 0
found = False
while attempt < 5:
attempt += 1
response = responses[attempt - 1]
if response is None:
print(f"attempt {attempt}: no response, retrying")
continue # skip the rest of this iteration
print(f"attempt {attempt}: got response {response}, done")
found = True
break # success, exit the loop
if not found:
print("reached the maximum number of attempts")
Putting attempt += 1 at the top of the loop is the key. With this layout, even if continue or break exit early, the counter never gets skipped, so the "up to 5 attempts" guarantee holds.
Choosing between for and while
for and while are both loops, but they suit different situations. When you can't decide, recall this table.
| When you want to… | Best fit | Why |
|---|---|---|
| Process every element of a list, dict, etc. | for | Top-to-end iteration reads naturally |
| Repeat exactly N times from 0 to N-1 | for + range(N) | The count is stated explicitly as a number |
| End on a complex condition where the count isn't known | while | The condition itself drives the loop |
| Retry until an external response succeeds | while + break | You can exit immediately on success |
| Process user input or a queue until empty | while | It naturally ends the moment it goes empty |
In this article, we covered the basics of while, the termination conditions that prevent infinite loops, controlling flow with break / continue, and how to choose between for and while.
With if / for / while covered, you've learned the fundamental control flow.
Knowledge Check
Answer each question one by one.
Q2What's the most important thing to do to avoid an infinite loop in while?
Q3Which is the most appropriate way to choose between for and while?