Python while Loop
Loop Satellite
While Loops
Use `while` when you don't know the number of iterations in advance.
Patterns
# Process until empty
while queue:
job = queue.pop(0)
handle(job)
# Read until end of input
while True:
data = stream.read()
if not data:
break
process(data)
# Countdown
count = 5
while count > 0:
print(count)
count -= 1
while/else
The else clause runs when the condition becomes False (not on break):
attempts = 3
while attempts > 0:
if try_connect():
break
attempts -= 1
else:
print("All attempts failed")
Tips
- Always ensure the loop condition eventually becomes
False. - Use
breakto exit sentinel loops. - Use
time.sleep(interval)in polling loops to avoid busy-waiting. - Prefer
forloops when iterating over a known sequence.