Skip to content
Mastering Python’s else: Using else with for, while, and try
Fundamentals 5 min read

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.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

control flowfor-elseelse clausetry-elsewhile-else
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.