break stops a loop immediately and continues with the code after it. It's how you exit early — the moment you've found what you were looking for, there's no reason to keep looping.
Stopping a search
The classic use: scan until you find a match, then stop:
for n in [4, 7, 2, 9, 1]:if n > 8:print("found one over 8:", n)break # leave the loop right away# execution continues here after the break
break only exits one loop
for row in grid:for cell in row:if cell == target:print("found")break # exits the inner loop only# outer loop continues with the next row
Key takeaways
- 01break exits the nearest enclosing loop immediately.
- 02Ideal for stopping a search once a match is found.
- 03In nested loops it only exits the innermost loop.
- 04To break out of nested loops, use a flag or a function with return.
