Topic 42 of 64
While Logic
Overview
While loops run a block as long as a condition is true. They are ideal for event-driven loops, retries, game loops, and situations where you don't know the number of iterations in advance.
Syntax
python
# Basic while
count = 0
while count < 5:
print(count)
count += 1 # 0, 1, 2, 3, 4
# While with else (runs if loop ended normally, not via break)
n = 10
while n > 0:
n -= 3
else:
print("Loop ended") # always runs
# Infinite loop with break
while True:
user_input = input("Type 'quit' to exit: ")
if user_input == "quit":
breakCommon Pitfalls
- Always ensure the loop condition eventually becomes False or include a break — infinite loops block the thread.
- Python's while/else runs the else clause only if the loop exits normally (no break) — useful for 'not found' search patterns.
- Interview tip: Prefer for loops when the number of iterations is known; use while when looping until an event occurs.
Real-World Example
Retry logic with exponential backoff
example
python
import time
def fetch_with_retry(max_retries: int = 3) -> str:
attempt = 0
while attempt < max_retries:
try:
# Simulated flaky request
if attempt < 2:
raise ConnectionError("Timeout")
return "Success!"
except ConnectionError:
attempt += 1
wait = 2 ** attempt
print(f"Retry {attempt}, waiting {wait}s")
time.sleep(wait)
return "Failed after retries"
print(fetch_with_retry())