while
Executes a block of code repeatedly as long as a given condition evaluates to a truthy value. The condition is checked before each iteration.
Syntax
while condition:
# body
condition is any expression. The body is indented one level (four spaces). No parentheses are required around the condition.
n = 3
while n > 0:
print(n)
n -= 1
# output: 3, 2, 1
while...else
Python allows an optional else clause on while loops. The else block runs once when the condition first evaluates to falsy — it does not run if the loop was exited via break or return.
i = 0
while i < 3:
print(i)
i += 1
else:
print("done")
# output: 0, 1, 2, done
i = 0
while i < 3:
if i == 1:
break
i += 1
else:
print("done")
# output: (nothing after break — else is skipped)
A common use case is the “search or not found” pattern:
nums = [1, 2, 3, 4, 5]
while nums:
if nums.pop() == 99:
print("found 99")
break
else:
print("99 not found")
# output: 99 not found
break and continue
break exits the innermost loop immediately and skips the else clause if present.
count = 0
while count < 10:
count += 1
if count == 5:
break
print(count)
# output: 1, 2, 3, 4
continue skips the rest of the current iteration and jumps straight to the condition check.
count = 0
while count < 5:
count += 1
if count == 3:
continue
print(count)
# output: 1, 2, 4, 5
Infinite Loops
while True: creates an infinite loop that runs until explicitly broken.
import random
attempts = 0
while True:
attempts += 1
if random.random() > 0.95:
break
print(attempts)
# output: varies (stopped when random() > 0.95)
When nesting while loops, break only exits the innermost level. Python does not have labeled break. To break out of multiple loop levels, use a flag variable, return from a function, or raise an exception.
found = False
i = 0
while i < 3 and not found:
j = 0
while j < 3:
if (i, j) == (1, 2):
found = True
break
j += 1
i += 1
print(i, j)
# output: 1 2
Truthiness
Any expression can be used as a condition. Python checks truthiness directly — not just boolean values.
Falsy values: False, None, 0, "", [], {}, ().
Everything else is truthy.
# Loop until list is empty
items = [1, 2, 3]
while items:
print(items.pop())
# output: 3, 2, 1
# Loop until None (cache miss sentinel)
cache = {"key": "value"}
while cache.get("key"):
print(cache.pop("key"))
# output: value
Walrus Operator (:=)
The walrus operator (Python 3.8+, PEP 572) assigns and returns a value in a single expression. Useful in while conditions to avoid repeated function calls.
# Read lines until blank — no double call to readline()
import sys
data = sys.stdin
while (line := data.readline().strip()):
print(f"got: {line}")
# Prompt until valid input
while (resp := input("(y/n): ")) not in ("y", "n"):
pass
print("thanks")
Summary
| Feature | Syntax |
|---|---|
| Basic loop | while condition: |
| Exit on condition | while condition: ... else: |
| Exit immediately | break |
| Next iteration | continue |
| Infinite loop | while True: |
| Assignment in condition | while (x := expr): |
See Also
/reference/keywords/for-keyword/—forloops and when to prefer them overwhile/reference/keywords/break-keyword/—breakstatement details