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
elsemeans “run on the last iteration.” - Confusing the loop’s
elsewith anifstatement’selse. - Forgetting that
breaksuppresses the loop’selse.
Key Takeaways
- A loop’s
elseblock executes when the loop completes normally withoutbreak. - All inventory IDs are checked and no
breakoccurs, so Not found prints. - Avoid this mistake: Assuming loop
elsemeans “run on the last iteration.”.