Python while Loop
In this page:
while condition:
# loop body
update_variable
Simple While Loop
A while loop re-checks its condition before every pass and keeps running its body as long as that condition stays True; the moment it evaluates to False, the loop exits and execution continues after it.
Example: Simple While Loop
count = 0
while count < 3: # loop continues as long as this stays True
print(count)
count += 1 # without this, the condition would never become False
Decrementing Loops
Subtracting from the loop variable each iteration lets a while loop count downward — a common pattern for countdowns, retry limits, or processing a shrinking range of values until it reaches zero.
Example: Decrementing Loops
countdown = 3
while countdown > 0:
print(countdown)
countdown -= 1 # counts down toward zero each iteration
Using Flags for Loop Control
Using a boolean variable as the loop condition — while running: — lets code anywhere inside the loop body set that flag to False to end the loop, which is more flexible than a fixed numeric condition when the stop point depends on runtime logic.
Example: Using Flags for Loop Control
running = True
while running: # loop continues while the flag is True
print("Running")
running = False # setting the flag False ends the loop next check
While Loop with Lists
A while loop paired with .pop() is a common way to drain a list one item at a time, since the list shrinks with each iteration and the loop naturally ends once it's empty.
Example: While Loop with Lists
items = [1, 2, 3]
while items: # loop continues while the list is non-empty
print(items.pop()) # removes and prints the last item, shrinking the list
Mathematical Loops
Multiplying or dividing the loop variable each pass (rather than adding or subtracting a fixed amount) produces exponential growth or decay, useful for simulations or algorithms like binary search that repeatedly halve a range.
Example: Mathematical Loops
value = 1
while value < 100:
print(value)
value *= 2 # doubles each iteration, growing exponentially
- Forgetting to update the loop variable, so
while i < 5:never ends and runs forever. - Off-by-one conditions such as
while i <= 5when starting at 0, giving one extra iteration. - Modifying a list while looping over it with
whileandpop/remove, which skips elements or ends early.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: