Content · Programming · Python

Python for-else and while-else Explained

A loop’s else block executes when the loop completes normally without break. It is not triggered by each failed if; think of it as a “not interrupted” branch. Learn with a clear example and common mistakes to avoid.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

This guide explains for-else and while-else Explained through a focused example and practical reasoning. No prior knowledge of this specific operation is required.

Understanding the Concept


A loop’s else block executes when the loop completes normally without break. It is not triggered by each failed if; think of it as a “not interrupted” branch.

When You Would Use This


Search a list and announce when a value was not found.

Step-by-Step Example


inventory_ids = [11, 14, 17]
requested_id = 20
for inventory_id in inventory_ids:
    if inventory_id == requested_id:
        print("Found")
        break
else:
    print("Not found")

How the Example Works


All inventory IDs are checked and no break occurs, so Not found prints. If the requested ID were 14, break would skip the loop’s else.

Example Output


Not found

Try It Yourself


Try the target 11 and explain why the final message changes.

Common Beginner Mistakes


  • Assuming loop else means “run on the last iteration.”
  • Confusing the loop’s else with an if statement’s else.
  • Forgetting that break suppresses the loop’s else.

Key Takeaways


  • A loop’s else block executes when the loop completes normally without break.
  • All inventory IDs are checked and no break occurs, so Not found prints.
  • Avoid this mistake: Assuming loop else means “run on the last iteration.”.
Share this resourceSend this page to someone who may find it useful.