[Rod Stephens Books]
Index Books Python Examples About Rod Contact
[Mastodon] [Bluesky]
[Build Your Own Ray Tracer With Python]

[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

Title: Use a loop's else block in Python

[Output from a Python program that demonstrates several loop else blocks]

This is example shows how to use the humble for loop's else block. That block executes if the loop terminates normally by processing all of the items in the for part. If the code teleports out of the loop with a break statement, return statement, or some other shenanigans, the code skips the else block.

Here's the example's code.

# Use a break statement to bypass else. for i in range(5): print(i, end=' ') if i == 3: break else: print('Else 1') print() # Use a while loop with a break statement. i = 0 while i < 10: print(i, end=' ') if i == 3: break i += 1 else: print('Else 2') print() # Use an except block to bypass else. try: for ch in ['A', 'B', 'C', 'D', 'E', 'F']: print(ch, end=' ') if ch == 'E': raise Exception() else: print('Else 3') except: print('Except') # Finish the loop. for i in range(6): print(i, end=' ') else: print('Else 4')

This program executes four loops, all with else blocks.

The first loop uses a break statement to end early, so it skips the else block and doesn't print "Else 1."

The second loop is similar to the first except it uses a while loop, just to show that while loops have else blocks too.

The third loop is contained in a try except block. When the loop raises an error, the program skips the else block and the except block executes.

Finally, the third loop runs to completion so it prints "Else 4."

Here's the program's output.

0 1 2 3 0 1 2 3 A B C D E Except 0 1 2 3 4 5 Else 4

I think the loop's else clause is mostly intended for situations where you're looking for something in a list. You look through the list and, if you find what you're looking for, you break out. If you're like U2 and you still haven't found what you're looking for, the else block executes.

Download the example to experiment with it.

© 2025 Rocky Mountain Computer Consulting, Inc. All rights reserved.