Mastering Python’s else: Using else with for, while, and try
This article explains how Python’s else clause works beyond simple if statements, showing its use with for, while, and try blocks, complete with clear code examples and guidance on when the else block is executed.
In Python, the else clause is not limited to if statements; it can also be attached to for, while, and try constructs, providing a way to run code only when the loop completes normally or no exception occurs.
Using else with if
a = '12'
if a == '123':
print(a)
else:
print('Error!')While this is the most familiar form, the same else keyword has broader applications.
Using else with for loops
The else block runs only if the loop finishes without encountering a break.
my_list = ['apple', 'pear', 'orange', 'banana']
for item in my_list:
if item == 'banana':
print('Found!')
break
else:
raise ValueError('No banana flavor found!')If the list does not contain 'banana', the loop ends naturally and the else clause raises an error.
my_list = ['apple', 'pear', 'orange']
for item in my_list:
if item == 'banana':
print('Found!')
break
else:
raise ValueError('No banana flavor found!')Without the else, you would need an extra flag variable to detect the missing item.
Using else with while loops
The else block executes only when the while condition becomes false, not when the loop is exited via break.
a = 'apple'
while a == 'banana':
pass
else:
raise ValueError('No banana flavor found!')Using else with try statements
In a try/except/else construct, the else block runs only if no exception is raised in the try block.
try:
dangerous_call()
except OSError:
log('OSError...')
else:
after_call()This pattern separates normal flow from error handling, ensuring after_call() runs only when the risky operation succeeds.
Summary of else behavior
for : else runs when the loop completes without a break.
while : else runs when the loop exits because its condition is false, not via break.
try : else runs only when no exception is raised in the try block.
If control leaves the compound statement via return, break, continue, or an exception, the else clause is skipped.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
