Back to course

The `else` Clause in Loops (Advanced Flow Control)

Python Programming: The 0 to Hero Bootcamp

Loop else Clauses

Python allows an else clause to be attached to both for and while loops. This else block executes only if the loop completes without being terminated by a break statement.

When is this useful?

It's commonly used when searching for an item in a sequence. If the loop completes normally, it means the item was not found.

Example 1: Loop Completed Successfully (Item Not Found)

python items = ['A', 'B', 'C'] search_item = 'D'

for item in items: if item == search_item: print(f"{search_item} found!") break else: # This runs because 'break' was never hit print(f"{search_item} not found in the list.")

Example 2: Loop Interrupted (Item Found)

python search_item = 'B'

for item in items: if item == search_item: print(f"{search_item} found!") break # The break prevents the else block from executing else: print("Item not found.")

Output: B found!