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

Handling Loop Exhaustion With Else

Learners will be able to execute specific code blocks after a while loop finishes naturally without being interrupted by a break statement.

Handling Loop Exhaustion With Else

In this lesson, you will learn how to trigger a specific piece of code only when your while loop finishes its work naturally, without being stopped by a break statement.

The "Else" Surprise

Usually, we think of the else keyword as part of an if statement. However, in Python, you can attach an else block directly to a while loop. This block acts like a "completion reward"—it runs if, and only if, the loop condition becomes False on its own.

If your loop hits a break statement, Python considers the loop "interrupted," and it will skip the else block entirely. This is incredibly useful for searching tasks where you need to report whether you found something or if you reached the end of your search empty-handed.

Seeing it in Action

Imagine you are checking a list of inventory counts to see if any items are out of stock. If you find one, you break; if you reach the end without finding any, you want to print a success message.

inventory = [5, 2, 0, 8]
index = 0

while index < len(inventory):
    if inventory[index] == 0:
        print("Out of stock found!")
        break
    index += 1
else:
    print("All items are in stock.")

In the example above, the else block will not run because the break statement triggers when the code hits 0. If you removed the 0 from the list, the loop would finish normally, the while condition would become False, and the code inside the else block would execute, printing "All items are in stock."

This pattern is a cleaner way to handle "did I finish the loop or was I interrupted?" logic without needing to create extra tracking variables like found = False.

Key Takeaway: The else block attached to a while loop runs only when the loop condition naturally becomes False, skipping it entirely if the loop is terminated by a break.