How it works
The condition is checked before the first iteration, so the body can run zero times. Inside the body, update the state that controls repetition or reach a break. Otherwise a condition that stays true can cause an endless loop.
continue skips the rest of the body and returns to the condition check. If a counter update comes after continue, it may never run; place essential progress updates where every relevant path reaches them.
The optional else clause runs when the condition becomes false, including when it was false initially. break skips else. An exception or return leaving the loop also prevents normal completion; else does not mean “the last if was false”.
Common mistakes and boundaries
Use for for direct iteration over values, even if their count is unknown. Avoid manual indexes when the value itself is all you need.
Do not use a tight loop to wait for a network response or time to pass. Real waiting needs the appropriate blocking or asynchronous API. A retry loop should have an explicit stopping policy.
Try it yourself
Change the search example to find 5 and then 4. Explain why else runs only for the missing target. Next test an empty list, which should also report that the target was not found.
Syntax
while condition:
# update the state or breakExamples
Basic While Loop
Repeating a block of code until a counter condition becomes False.
count = 0
while count < 5:
print(count)
count += 1
print("Done")- The condition is checked before printing. Incrementing count eventually makes it false, so the loop prints five numbers and then Done.
- Expected output: 0 1 2 3 4 Done
While Loop with break
Using while True with break to create a loop that exits based on internal logic rather than a simple counter.
attempts = 0
while True:
attempts += 1
guess = attempts # simulate a guess
if guess == 3:
print(f"Found it after {attempts} attempts")
break- The simulation changes guess on every iteration. break exits as soon as the third attempt succeeds.
- Expected output: Found it after 3 attempts
Input Validation Loop
A very common real-world use: repeat until the user provides valid input.
while True:
age_input = input("Enter your age: ")
try:
age = int(age_input)
except ValueError:
print("Please enter an integer")
continue
if age < 0:
print("Age cannot be negative")
continue
break
print(f"Age accepted: {age}")- This terminal example separates integer parsing from the nonnegative-age rule. It deliberately leaves EOF/interrupt handling to the caller; the input() guide shows an EOF-aware version.
- Expected output with the sample input below: Enter your age: Please enter an integer Enter your age: Age cannot be negative Enter your age: Age accepted: 21
- Run in a local terminal or an editor with console input. Sample input, one response per line: abc -1 21
While with else
The else block runs only if the loop completes without hitting a break.
numbers = [1, 3, 5, 7]
target = 4
i = 0
while i < len(numbers):
if numbers[i] == target:
print("Found!")
break
i += 1
else:
print("Target not found in the list")- The index advances after every unsuccessful comparison. The missing target allows the condition to become false and the else message to run.
- Expected output: Target not found in the list
Best practices
- Make the exit condition explicit and ensure each iteration can make progress.
- Prefer for when consuming an iterable directly.
- Check continue paths for skipped counter updates.
- Use loop else only when its no-break meaning makes the code clearer.
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference