This guide explains break Statement: Stop a Loop through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
break exits the innermost enclosing loop immediately. It is useful when an item has been found or a cancellation condition is met; statements after break in that iteration do not run.
When You Would Use This
Stop looking once a matching order is found.
Step-by-Step Example
order_numbers = [102, 108, 113, 120]
for order_number in order_numbers:
if order_number == 113:
print("Order located")
break
print("Checking:", order_number)
How the Example Works
The program checks 102 and 108, then finds 113 and exits. It never checks 120.
Example Output
Checking: 102
Checking: 108
Order located
Try It Yourself
Change the target to 120 and trace the output.
Common Beginner Mistakes
- Expecting
breakto exit all nested loops. - Using
breakoutside a loop. - Assuming the loop’s
elseblock runs afterbreak.
Key Takeaways
breakexits the innermost enclosing loop immediately.- The program checks 102 and 108, then finds 113 and exits.
- Avoid this mistake: Expecting
breakto exit all nested loops.