Skip to main content
Albero Academy

break

Exit a loop early when you have what you need.

Flow Control6 min

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.

The classic use: scan until you find a match, then stop:

stop at the first match
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

inner break, outer continues
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

  1. 01break exits the nearest enclosing loop immediately.
  2. 02Ideal for stopping a search once a match is found.
  3. 03In nested loops it only exits the innermost loop.
  4. 04To break out of nested loops, use a flag or a function with return.

Finished this chapter?

Mark it complete to track your progress through Python.