Python While Loop
Tutorial 15 of 65 · pythondeck.com Python course
while repeats while a condition is truthy. Use break to leave early, continue to skip to the next iteration. An optional else clause runs if the loop ends without a break.
While loops repeat a block while a condition remains true. They suit unknown iteration counts: reading until EOF, retrying with backoff, or game loops until quit. Network clients and daemons often loop until a shutdown flag flips or a timeout elapses.
Every while loop needs a clear progress path toward falsy condition, or you risk an infinite loop that blocks the interpreter.
Syntax: while condition: body; else runs if loop exits without break.
break exits the loop; continue skips to next iteration.
Infinite loop pattern while True: with internal break is common for menus.
Combine with try/except for retry limits on I/O.
Counter-controlled loops can often be for loops instead—choose the clearer form.
Watch CPU-heavy while True without sleep in event loops or servers.
The while-else construct is rare; many teams avoid else on loops for readability. Polling should include sleep (time.sleep) or async await to avoid busy-wait.
State machines sometimes replace nested while/break logic with explicit states.
Prefer for on known collections; while True menus break on quit after validating input().
Forgetting to update the variable tested in the while condition.
Busy-waiting on a flag without timeout or sleep.
Using while to iterate a list—prefer for or enumerate.
Nested while loops without break strategy—hard to debug exit paths.
Ensure the condition eventually becomes false; use counters or deadlines for safety.
Extract loop bodies into functions when indentation exceeds two or three levels.
Prefer for over index-manipulation while loops when traversing sequences.
Log iteration counts in long-running loops for observability.
Cap retry loops with a max attempt counter so transient errors cannot spin forever.
Re-read the examples below with these ideas in mind; change variable names and inputs to match your own project.
The program below demonstrates countdown. Read the comments on each line, run the code, then change names or values to see how the output shifts.
# Example: Countdown
# Run in the REPL or save as a .py file and execute with python.
n = 5
while n > 0:
print(n)
n -= 1
print("go!")
This sample walks through break in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.
# Example: break
# Run in the REPL or save as a .py file and execute with python.
import random
while True:
r = random.randint(1, 6)
print(r)
if r == 6:
break
Here is a hands-on illustration of while/else. Follow the inline comments first; only then execute the snippet and compare the result with what you expected.
# Example: while/else
# Run in the REPL or save as a .py file and execute with python.
x = 17
d = 2
while d * d <= x:
if x % d == 0:
print("composite")
break
d += 1
else:
print("prime")
The program below demonstrates sentinel loop. Read the comments on each line, run the code, then change names or values to see how the output shifts.
# while repeats until the condition becomes False
total = 0 # accumulator
n = 1 # counter start
while n <= 5: # inclusive upper bound
total += n # add current number
n += 1 # advance counter
print(total) # sum 1..5 = 15
queue = [10, 20, 30] # process until empty
while queue: # empty list is falsy
item = queue.pop(0) # FIFO using pop(0)
print("processed", item) # log each item
This sample walks through break continue in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.
# break exits loop; continue skips to next iteration
nums = [3, 8, 2, 9, 4, 7] # search data
target = 9 # value to find
idx = 0 # manual index
while idx < len(nums): # bounds-safe loop
if nums[idx] == target: # match found
print("found at", idx) # report index
break # stop scanning early
idx += 1 # move to next index
else: # runs only if no break
print("not found") # not executed here
print("done") # after loop