Python while Loop
In this page:
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:
print(count)
count += 1
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
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:
print("Running")
running = False
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:
print(items.pop())
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
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: