Using else Clauses with for and while Loops in Python
Learn how Python loop else clauses work with for and while loops, including normal completion, break, continue, searches, validation, and common mistakes.
Python allows an optional else block after both for and while loops. A loop else clause runs when the loop completes normally—that is, when the loop finishes without executing break.
This behavior is useful for searches and validation checks. The loop examines values, and the else block handles the result when no early match or failure caused the loop to stop.
What a loop else clause means
A loop else clause is an else block written at the same indentation level as a for or while statement. It belongs to the loop, not to an if statement nested inside the loop.
for item in items:
# Loop body
pass
else:
# Runs if the loop ends without break
pass
For a for loop, normal completion means that the loop has consumed every item in its iterable. For a while loop, normal completion means that its condition has eventually become false. If break executes, the loop ends early and its else block is skipped.
| Construct | What controls the else block | Typical purpose |
|---|---|---|
if/else | Whether the condition is true or false | Choose between two conditional branches |
for/else | Whether the loop ends normally or uses break | Search an iterable and handle the not-found result |
while/else | Whether the condition becomes false or the loop uses break | Handle completion after repeated attempts or checks |
Normal completion of a for loop
A for loop iterates over an iterable, an object that provides values one at a time. Strings, lists, tuples, and ranges are examples of iterables.
In this example, the loop processes every character in a string. After the final character is processed, Python runs the loop's else block.
text = "cat"
for character in text:
print("Processing:", character)
else:
print("Finished processing every character")
Output:
Processing: c
Processing: a
Processing: t
Finished processing every character
The else message appears because the string was exhausted and no break statement interrupted the loop. The message runs after the final iteration, not during an additional iteration.
An empty iterable also completes normally
If a for loop receives an empty iterable, its body runs zero times, but the loop still completes normally. Therefore, its else block runs.
for item in []:
print(item)
else:
print("There were no items to process")
How break prevents loop else execution
break immediately exits the nearest enclosing loop. When a loop exits because of break, Python skips that loop's else block.
Here, the loop stops as soon as it finds the character a:
text = "cat"
a_found = False
for character in text:
print("Checking:", character)
if character == "a":
a_found = True
print("Found the target")
break
else:
print("The target was not found")
print("Search complete")
Output:
Checking: c
Checking: a
Found the target
Search complete
The loop never processes t, and the else message does not appear. The reason is not that the nested if was false or true; the reason is that the loop executed break.
The flag in this example is included for explanation. A loop else can often remove the need for a separate flag.
Searching a list with for else
A common use case is searching for a requested value. The loop handles a match and uses break to indicate that the search is over. The loop else reports the not-found outcome.
values = [12, 7, 25, 9]
target = 25
for value in values:
if value == target:
print("Found", target)
break
else:
print("Did not find", target)
Because 25 is present, the loop executes break and prints:
Found 25
If target is changed to 13, no iteration executes break. The loop reaches the end of the list and prints:
Did not find 13
Using else with while loops
A while loop repeats while its Boolean condition remains true. Its else block runs when the condition eventually becomes false without a break.
The basic syntax is:
while condition:
# Repeated body
pass
else:
# Runs if condition becomes false without break
pass
while loop that completes normally
This countdown decreases count until the condition count > 0 becomes false.
count = 3
while count > 0:
print(count)
count -= 1
else:
print("Countdown completed")
Output:
3
2
1
Countdown completed
The loop completes normally because the counter reaches zero. The condition is then false, so the else block runs.
while loop stopped with break
In the next example, the loop has attempts remaining, but a success condition causes an early exit.
attempts = 3
success = False
while attempts > 0:
print("Attempt remaining:", attempts)
if attempts == 2:
success = True
print("Operation succeeded")
break
attempts -= 1
else:
print("All attempts used without success")
Output:
Attempt remaining: 3
Attempt remaining: 2
Operation succeeded
The else message is skipped because break ended the loop. If the success condition never became true, the loop would eventually reduce attempts to zero, the condition would become false, and the else block would report that all attempts were used.
Loop control-flow distinctions
The important distinction is between normal completion and early termination.
- Normal completion: A
forloop exhausts its iterable, or awhilecondition becomes false. The loopelseruns. break: The nearest loop ends immediately. That loop'selsedoes not run.continue: The current iteration ends, and the next iteration begins. It does not suppresselseif the loop later completes normally.return: A function exits immediately. Control never reaches the loopelse.- Exception: An uncaught exception interrupts the loop. Control never reaches the loop
else.
| Loop type | How the loop ends | Does else run? | Reason |
|---|---|---|---|
for | Iterable is exhausted | Yes | Normal completion |
while | Condition becomes false | Yes | Normal completion |
for or while | break executes | No | The loop was stopped early |
for or while | continue executes, then the loop completes | Yes | continue skips only one iteration |
for or while | Function return occurs inside the loop | No | The function exits before reaching else |
for or while | An exception interrupts the loop | No | Normal loop completion did not occur |
continue does not prevent else
continue is not a loop-exit statement. It skips the remaining statements in the current iteration and checks whether another iteration should begin.
for number in range(3):
if number == 1:
continue
print(number)
else:
print("Loop completed without break")
Output:
0
2
Loop completed without break
The value 1 was skipped, but the loop still exhausted its iterable without break, so the else block ran.
Indentation and syntax
Python uses indentation, the whitespace at the start of a line, to define code blocks. A loop else must align with the for or while statement it belongs to.
for value in values:
if value < 0:
print("Invalid value")
break
else:
print("All values are valid")
Here, else aligns with for. The if block is nested inside the loop and has its own indentation.
This is a different construct:
for value in values:
if value < 0:
print("Invalid value")
else:
print("This individual value is not negative")
In the second example, the else belongs to if, because it is indented inside the loop and aligned with if. It is evaluated during each iteration. A loop else is evaluated only after loop control flow has concluded.
Validation with loop else
Loop else is useful when successful completion means that no invalid item was encountered. Put break on the invalid path, then use else for the all-valid outcome.
scores = [82, 91, 76, 88]
for score in scores:
if not 0 <= score <= 100:
print("Invalid score:", score)
break
else:
print("Every score is valid")
If an invalid score is found, break skips the success message. If every score passes the check, the list is exhausted normally and the success message runs.
This style avoids a separate flag variable, but clarity matters. If the loop's control flow is difficult to understand, a plainly named variable or a separate function may be easier for other readers to maintain.
Common mistakes and troubleshooting
The else block did not run
The most likely cause is that a break statement executed during an iteration. Trace the conditions leading to each break and decide whether the else block is intended only for the no-break outcome.
The else appears attached to the wrong statement
Check indentation. Align a loop else with its for or while statement. Align an if else with its if statement.
The not-found message appears even when a match exists
The matching branch may not execute break. If finding one match should end the search and suppress the not-found message, add break after handling the match.
names = ["Ada", "Linus", "Grace"]
target = "Grace"
for name in names:
if name == target:
print("Found", target)
break
else:
print("No match")
The else was expected to stop after continue
continue does not exit the loop. It only skips the rest of the current iteration. If no break executes and the loop eventually completes, the loop else still runs.
When to use loop else
- Searches: Use
breakwhen a requested item is found and useelsefor the not-found result. - Validation: Use
breakwhen an invalid item is encountered and useelseto report that every item passed. - Retry loops: Use
breakwhen an operation succeeds and useelsewhen all attempts finish without success. - Flag-free control flow: Use loop
elsewhen it clearly expresses the difference between “stopped early” and “completed normally.”
For more practice with the loop statements themselves, review Python for loops, Python while loops, the break statement, and the continue statement. Strings are useful iterable examples; see Python strings and accessing individual characters.
Exam-relevant summary
- Python permits
elseafter bothforandwhileloops. - A
for/elseblock runs when the iterable is exhausted withoutbreak. - A
while/elseblock runs when the condition becomes false withoutbreak. breakskips the loop'selseblock.continuedoes not skip the loop'selseblock if the loop later completes normally.- An
elsealigned withfororwhilebelongs to the loop; an indentedelsealigned withifbelongs to the conditional. - A
returnor an exception leaves the surrounding flow before the loopelsecan run.