As a companion to if/elif, else is the catch-all branch, requiring no condition of its own, that runs exactly when everything above it was falsy. Less well known: Python also allows an else clause on for and while loops, which runs only if the loop completes normally, without hitting a break — a pattern often used for 'search and report not-found' logic.
1Understanding else Statement
As a companion to if/elif, else is the catch-all branch, requiring no condition of its own, that runs exactly when everything above it was falsy. Less well known: Python also allows an else clause on for and while loops, which runs only if the loop completes normally, without hitting a break — a pattern often used for 'search and report not-found' logic.
A for/while's else clause only skips if the loop exits via break, so it's a clean way to run 'not found' logic without a separate found-flag variable — but many developers find it confusing, so a well-placed comment or a flag variable is sometimes clearer for readers unfamiliar with the feature.
age = 15
if age >= 18:
print("Adult")
else:
print("Minor")2Practical Example
Here is a real-world application of else Statement showing how it is used in production Python code.
numbers = [1, 3, 5, 7]
for n in numbers:
if n % 2 == 0:
print("Found an even number")
break
else:
print("No even numbers found")3Best Practices
Follow these guidelines when working with else Statement:
1. Use else as the final catch-all in an if/elif chain instead of leaving the fallback case implicit
2. Use a loop's else clause for 'ran to completion without break' logic instead of a manual found/not-found flag variable, when it improves clarity
3. Avoid relying on the for/while else clause in code likely to be read by developers unfamiliar with it, since it's a frequently misunderstood feature
Tip: A for/while's else clause only skips if the loop exits via break, so it's a clean way to run 'not found' logic without a separate found-flag variable — but many developers find it confusing, so a well-placed comment or a flag variable is sometimes clearer for readers unfamiliar with the feature.
age = 15
if age >= 18:
print("Adult")
else:
print("Minor")