Course contentsShow
← Python
Lesson 92 of 1,0602. Control Flow and LogicFree lesson

Executing Code After Loop Completion

Learners will be able to use the else clause to trigger specific actions only after a loop finishes its full execution.

Executing Code After Loop Completion

In this lesson, you will learn how to trigger specific actions automatically once a loop finishes its full execution using the else clause.

The Power of the else Clause in Loops

Usually, when you hear the word else, you think of if statements. However, Python allows you to attach an else block directly to a for loop. This else block behaves in a unique way: it runs only after the loop finishes iterating through all items naturally.

Think of it as a "completion notification." If your loop finishes every single cycle without being stopped, the code inside the else block will execute.

How it Works

Look at this example where we check a list for a specific item:

numbers = [1, 3, 5]

for num in numbers:
    if num % 2 == 0:
        print(f"Found an even number: {num}")
        break
else:
    print("No even numbers were found in the list.")

In this code, Python checks every number in the list. Since none of the numbers are even, the loop completes its full run. Because the loop was not interrupted by a break statement, the else block triggers and prints: "No even numbers were found in the list."

Important: The Role of break

The else block is a fantastic tool for search operations. If you use a break statement to exit a loop early (for example, if you find what you were looking for), the else block will not run. It only triggers when the loop reaches the end of its sequence entirely on its own.

This gives you a clean, readable way to handle "success" or "not found" scenarios without needing extra flags or complex variables to track the status of your loop.

Key Takeaway: The else clause attached to a loop executes only if the loop completes all its iterations without hitting a break statement.