Python `while` Loop: Syntax, Use Cases, and Common Patterns
Learn how Python's while loop works, when to use it over a for loop, and how break, continue, and the else clause shape its behavior.
Python’s while loop runs a block of code for as long as a condition stays true, with no fixed iteration count required.
That one design choice is what separates it from a for loop. A for loop knows its sequence upfront: iterate over this list, or count from 1 to 10. A while loop knows only its exit condition. You use it when the number of repetitions isn’t fixed in advance: waiting for user input, extracting digits from a number one at a time, or retrying a failing operation until it succeeds. The Python 3 reference states the rule simply: the expression is evaluated first; if true, the suite runs; then repeat.
What the while Loop Does
The loop evaluates a Boolean expression before each iteration. True means run the body. False means stop and move past the loop. The condition is tested again after every iteration, so the loop can terminate as soon as the state changes, even mid-sequence.
The practical split between while and for:
| Situation | Preferred loop |
|---|---|
| Iterate over a list, string, or dict | for |
| Count through a known range | for with range() |
| Stop when a condition changes | while |
| Wait for input or an external event | while |
| Extract digits from an integer | while |
Most placement coding questions that ask you to validate input, implement a search heuristic, or process digits one by one use while. Questions that ask you to sum a list, print a pattern, or traverse a sequence almost always use for.
Syntax and Basic Examples
The structure is two lines:
while condition:
# body — executes each time condition is True
The condition can be any expression that evaluates to a Boolean. The body must be indented by 4 spaces.
Counter pattern
i = 1
while i <= 5:
print(i)
i += 1
Output: 1, 2, 3, 4, 5 (one per line). Three things to observe:
iis initialised before the loop starts.- The condition checks
i <= 5. i += 1updates the variable on every iteration. Remove this line and the condition stays true forever.
Digit extraction pattern
This pattern appears in Armstrong number checks and sum-of-digits problems:
n = 1234
while n > 0:
digit = n % 10 # isolate the last digit
n = n // 10 # drop the last digit
print(digit)
Output: 4, 3, 2, 1. The loop ends when n reaches 0. The Armstrong number check uses exactly this pattern to pull each digit for the cube-sum calculation.
Accumulator pattern
numbers = [3, 7, 2, 8, 1]
total = 0
i = 0
while i < len(numbers):
total += numbers[i]
i += 1
print(total) # 21
More verbose than for for a fixed list, but structurally identical to the accumulation logic in the sum of array program, which shows both approaches side by side.
break, continue, and the else Clause
Three keywords modify loop flow:
break— exits the loop immediately, regardless of whether the condition is still true.continue— skips the rest of the current iteration and jumps back to the condition check.else— runs once after the condition becomes false, but is skipped if the loop exited viabreak.
break — early exit
i = 0
while i < 10:
if i == 5:
break
print(i)
i += 1
Output: 0, 1, 2, 3, 4. The loop stops at 5 without printing it. Everything after break in the body is ignored, and Python moves past the entire loop.
continue — skip one iteration
i = 0
while i < 6:
i += 1
if i % 2 == 0:
continue
print(i)
Output: 1, 3, 5. Even numbers are skipped because continue sends control back to the condition check before print runs. Notice that i += 1 comes before the continue check; place it after and you create an infinite loop where i never advances past the even value.
else — the search idiom
The else clause on a while loop is unusual enough to deserve its own example. It executes once when the condition becomes false, but is bypassed if a break fires:
target = 7
i = 1
while i <= 10:
if i == target:
print(f"Found {target}")
break
i += 1
else:
print("Not found in range")
If target is between 1 and 10, break fires and else is skipped. If target is 15, the loop runs to completion and else prints “Not found in range”. The Python tutorial on control flow documents this as the canonical idiom for a search loop with a clean “not found” branch, with no flag variable required.
Infinite Loops — Writing Them Safely
while True: is an intentional pattern, not a mistake. It runs until a break fires. Common legitimate uses:
- Input validation: keep prompting until the user provides a valid answer.
- Event polling: check a queue until a shutdown signal arrives.
- Retry logic: attempt an operation up to a fixed number of times.
The safety requirement is always the same: a break condition inside the body. Here is a retry-with-limit pattern:
attempts = 0
max_attempts = 3
while True:
user_input = input("Enter a number between 1 and 10: ")
attempts += 1
if user_input.isdigit() and 1 <= int(user_input) <= 10:
print(f"Valid: {user_input}")
break
if attempts >= max_attempts:
print("Maximum attempts reached.")
break
print("Invalid. Try again.")
The loop runs at most 3 times regardless of input. Both exit paths use break. Without either break, the loop never ends.
A loop without any break condition is a bug, not a pattern. If you find yourself writing while True: and then hunting for where the exit condition goes, add it before the body fills up. It’s easier to design the exit before writing the iteration logic.
Common Pitfalls
Three mistakes account for most while-loop bugs in placement submissions.
Forgetting to update the loop variable
i = 0
while i < 5:
print(i)
# missing: i += 1
This prints 0 forever. The condition i < 5 is always true because i never changes.
Off-by-one in the condition
# Intention: print 1 through 5
i = 1
while i < 5: # should be <= 5 or i < 6
print(i)
i += 1
Output stops at 4. The fix is i <= 5 or i < 6. Off-by-one errors are easier to catch when you trace through the first and last iteration explicitly before submitting.
Updating the variable after continue
i = 0
while i < 5:
if i == 2:
continue # i never increments past 2 — infinite loop
print(i)
i += 1
The continue jumps back to the condition check, but i is still 2. Move i += 1 to before the continue check, or restructure so the increment always runs.
For practice with the patterns covered here, Python basic programs has a set of beginner exercises where while and for loops appear side by side, making the trade-offs concrete.
The retry-with-limit pattern from the “Infinite Loops” section above is exactly what production LLM API wrappers use: send a request, check the response, break on success, retry up to max_attempts on a rate-limit or network error. Once the loop mechanics click, TinkerLLM at ₹299 is the natural next step: a Python-native playground where that same while True / break structure connects directly to live model calls, without the boilerplate of setting up API keys and client libraries from scratch.
Primary sources
Frequently asked questions
What is the difference between a while loop and a for loop in Python?
A for loop iterates over a sequence (list, string, range) and ends when the sequence is exhausted. A while loop runs as long as a condition is true, regardless of any sequence. Use for when the iteration count is known; use while when the stopping point depends on state that changes at runtime.
How does the else clause work with a while loop in Python?
The else block runs once after the condition becomes false, but is skipped entirely if the loop exits via break. It is most useful for search loops: if break fired, the target was found; if else ran, the search completed without finding it.
What causes an infinite loop in Python, and how do you stop it?
An infinite loop occurs when the while condition never evaluates to False. Common causes: forgetting to update the loop variable inside the body, or writing a condition that is always true without a break. Press Ctrl+C in the terminal to interrupt a runaway loop.
Does Python have a do-while loop?
No. Python does not have a do-while construct. You can replicate the behavior with while True: and a break at the end of the loop body, which guarantees the body runs at least once before any condition is checked.
What happens if the while loop condition is false from the very start?
The loop body never executes. Python checks the condition before the first iteration; if it is already False, the loop is skipped and control moves to the next statement after the loop, or to the else block if one is present.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)