While Loops
A while loop keeps running a block of code as long as the condition is true. How many times? No way to know up front. It depends on when the condition goes false or when you hit break.
while is for when you’re waiting on something: user input, a flag, some condition. Get the condition and the
elsebit right and you’ll avoid a lot of headaches. Also makes it obvious when to use while instead of for.
Syntax and Structure
General form:
while condition:
# loop body - executed while condition is truthy
statement_1
statement_2condition– Checked before every run. True and the body runs; false and you’re out.- Loop body – The indented block under
while. Something in there had better make the condition false (or callbreak), or you’re stuck forever.
Example:
n = 0
while n < 6:
print(n)
n += 2
# Prints: 0, 2, 4So n starts at 0 and goes up by 2 each time. Once n hits 6 the condition fails and we’re done.
Condition Evaluation
The condition is checked before every iteration, including the very first. False from the start? Body never runs.
count = 10
while count < 6:
print(count)
count += 2
# Nothing is printed - condition is false from the startTruthiness: Whatever you put there is treated as true or false. Falsy stuff (False, 0, "", [], {}, None) ends the loop. Anything else and it keeps going. So while True: runs until something inside does break.
data = [2, 4, 6]
while data:
x = data.pop()
print(x)
# Prints: 6, 4, 2 - loop stops when data is empty (falsy)Updating State and Avoiding Infinite Loops
Loop stops when the condition turns false or the body hits break. Neither happens? You’ve got an infinite loop.
Common mistake: Not updating whatever the condition depends on.
# BAD - infinite loop: n never changes
n = 0
while n < 6:
print(n)
# n stays 0; n < 6 is always trueFix: Update that variable (or whatever the condition reads) inside the body, or make sure you hit break when you’re done.
n = 0
while n < 6:
print(n)
n += 2Off-by-one: Updating at the start of the body vs the end changes what you see and how many times you go around.
# Update at end of body - 0, 2, 4 printed
n = 0
while n < 6:
print(n)
n += 2
# Update at start of body - 2, 4, 6 printed (6 is still printed before check)
n = 0
while n < 6:
n += 2
print(n)break and continue
break – Bails out of the loop right away. No more iterations, and any else on the loop is skipped.
n = 0
while n < 10:
if n == 6:
break
print(n)
n += 2
# Prints: 0, 2, 4 - then exitscontinue – Skips the rest of this round and jumps back to the condition. Still true? Next iteration runs.
n = 0
while n < 8:
n += 2
if n == 4:
continue
print(n)
# Prints: 2, 6, 8 - 4 is skippedPlacement of updates: With continue in the mix, do whatever has to happen every time before you hit it. Otherwise the loop variable might never change and you’re in infinite-loop territory.
The else Clause on while
while loops can have an else too. The else runs only when the loop exits the normal way (condition went false). Exit via break and the else is skipped.
People often think else means “condition is false.” It doesn’t. It means “we didn’t break.”
n = 0
while n < 4:
print(n)
n += 2
else:
print("Loop finished normally")
# Prints: 0, 2, then "Loop finished normally"n = 0
while n < 8:
if n == 4:
break
print(n)
n += 2
else:
print("Loop finished normally")
# Prints: 0, 2 only - else is not executed because of breakHandy in search loops: put your “not found” handling in else. So break = found, else = not found.
target = 6
vals = [2, 4, 8, 10]
i = 0
while i < len(vals):
if vals[i] == target:
print("Found at index", i)
break
i += 1
else:
print("Not found")
# Prints: Not found - 6 is not in valsWhen to Use while vs for
| Situation | Prefer |
|---|---|
| Iterating over a known sequence (list, range, string, etc.) | for |
| Number of iterations depends on runtime condition or input | while |
| “Loop until a sentinel value” (e.g. user types “quit”) | while |
| Counting with a simple range | for with range() |
| Complex termination (multiple conditions, flag, or event) | while |
| Parsing or reading until end of stream or condition | while |
Rule of thumb: Got a sequence or a known count? for. Waiting on a condition or input? while.
# Clear with for - known sequence
for x in [2, 4, 6, 8]:
print(x)
# while - iterations depend on condition
total = 0
while total < 20:
total += 4
print(total)Common Patterns
Sentinel Loop
The loop runs until a special “sentinel” value is seen (e.g. empty string, “quit”, or a sentinel object). The condition checks for “not the sentinel.”
# Read lines until the user enters "quit"
line = input("Enter a line (or 'quit' to stop): ")
while line != "quit":
print("You said:", line)
line = input("Enter a line (or 'quit' to stop): ")Counting or Accumulation
Bump a variable each time (count or sum). Stop once you hit your threshold.
s = 0
k = 0
while s < 24:
k += 2
s += k
# Stops when cumulative sum s reaches or exceeds 24Input Validation
Keep prompting until the input is good. Condition: “still invalid.” Once it’s valid, you exit.
# Prompt until the user enters an even number
valid = False
while not valid:
raw = input("Enter an even number: ")
if raw.isdigit() and int(raw) % 2 == 0:
valid = TrueDrain a Collection
Loop while the collection’s non-empty; grab or process one item each time. The condition is just the collection (empty is falsy, non-empty is truthy).
stack = [2, 4, 6, 8]
while stack:
top = stack.pop()
print(top)
# Prints: 8, 6, 4, 2Nested while Loops
Put a while inside another while (or for) and you’ve got nesting. break and continue only affect the innermost loop they’re in.
row = 0
while row < 2:
col = 0
while col < 4:
print(row, col)
col += 2
row += 2
# (0,0), (0,2), (2,0), (2,2)To escape nested loops: set a flag before break in the inner loop and check it in the outer, or put the whole thing in a function and return.
found = False
i = 0
while i < 4 and not found:
j = 0
while j < 4:
if i * 10 + j == 22:
found = True
break
j += 2
i += 2Emulating do-while
Python doesn’t have do-while (run once, then check). Same effect: run at least once, then loop. The usual trick is while True with a break:
# Body runs at least once; then loop while condition (e.g. drain until empty)
queue = [2, 4, 6]
while True:
if not queue:
break
x = queue.pop(0)
print(x)
# Prints: 2, 4, 6 - body always runs once per item; exit when queue is emptyYou could duplicate the first run before the loop and then use a normal while, but that’s redundant. while True plus break is the standard move when you need at least one run.
Tricky Behaviors
Condition checked before body
The condition is evaluated before every iteration, including the first. False on first evaluation → body never runs.
Truthiness of condition
The condition is interpreted in a boolean context. Falsy values (False, 0, "", [], {}, None) end the loop; truthy values keep it running. So while data: stops when data is empty.
Infinite loop
If the condition never becomes false and break is never hit, the loop runs forever. Update the loop variable (or whatever the condition uses) in the body, or reach break.
Off-by-one / update placement
Updating at the start vs the end of the body changes which values you see and how many times the loop runs.
continue and updates
If you update the loop variable only after continue, that update is skipped when continue runs - you can get an infinite loop. Put updates before continue.
else and break
The else block runs only when the loop exits because the condition became false. It does not run when you exit via break. So else means “completed without breaking.”
Choosing while when for fits
If you have a sequence or a known count, for is clearer. Using while with a manual index is easy to get wrong (off-by-one, forgotten update).
Modifying a sequence while iterating
Adding or removing items while looping can skip or repeat indices. Loop over a copy or go in reverse when removing.
break in nested loops
break exits only the innermost loop. Use a flag (set before break, check in outer loop) or return from a function to exit multiple levels.
Floating-point conditions
Floats in the condition (e.g. while x < 1.0:) can misbehave due to rounding. Prefer integer counters or an explicit tolerance.
Interview Questions
What is the syntax of a while loop, and what must be true for the loop to terminate?
while condition: plus an indented body. The loop runs while the condition is true. To stop, the condition must become false or the body must run break; otherwise it runs forever.
When is the condition evaluated? Can the loop body run zero times?
Before every iteration, including the first. False the first time → body never runs (zero iterations).
Can the while condition be something other than a comparison?
Yes. Any expression; its truth value is used. while data:, while flag:, while True: are all valid.
Why might a while loop run forever?
The condition never becomes false and break is never hit. Usually: the loop variable is never updated, or it’s updated in the wrong place or wrong direction.
What is the effect of break in a while loop?
break exits the loop immediately. No more iterations; any else on the loop is not run.
What is the effect of continue? Why must updates be placed before continue in some loops?
continue skips the rest of this iteration and goes back to the condition. If the loop variable is updated only after continue, that update is skipped when continue runs - so the variable may never change and you get an infinite loop. Put updates before continue.
What does the else clause on a while loop do?
Runs only when the loop ends because the condition became false. It doesn’t run when you exit with break. So else = “no break” - handy for “not found” in search loops.
When would you use while instead of for?
When iterations aren’t known in advance: sentinel value, input validation, parsing until a condition, or when termination depends on something complex or changing. Use for when you’re iterating over a known sequence or a fixed number of times.
What are common patterns for while loops?
Sentinel (until a special value), counting or accumulation (until a threshold), input validation (repeat until valid), and draining a collection (while stack: with pop()).
How do you exit from nested while loops?
break exits only the innermost loop. Set a flag before break in the inner loop and check it in the outer; or put the loops in a function and use return.
How do you emulate do-while in Python?
while True: and break when your stopping condition is met. Body runs at least once, then you check and break. You could run the “first iteration” once before a normal while instead, but that duplicates code.