Break
Python · Loops
Theory
break immediately ends the nearest enclosing for or while loop. The rest of the current pass is skipped, no further passes happen, and execution jumps to the first statement after the loop. In the example, the loop is meant to run for n = 0 to 9, but when n reaches 3 the condition n == 3 is true, break runs, and the loop stops, so the output is only 0, 1 and 2. The 3 is never printed, because break comes before print in the body.
break is most useful in searches: stop scanning as soon as you find what you need instead of checking the remaining items. It also exits deliberate infinite loops such as while True:. It affects only the innermost loop, so in nested loops the outer loop keeps going. If a loop has an else clause, break skips that else. Using break outside a loop is a SyntaxError.
Why we use it
Continuing to loop after you already have your answer wastes time, especially on large data. break lets the loop stop the moment a match is found, an error appears, or a limit is reached.
When to use it
Use break to stop a search on the first match or to exit a while True loop. If you just need to know whether any item matches, any() or the in operator is shorter. To skip a single item instead of stopping, use continue.
How it works
- for n in range(10): starts
- Take the next n
- Is n == 3? Yes: break: leave the loop immediately. No: print(n) and continue looping.
- Repeat for the next n
- After the loop: printed 0, 1, 2
Syntax
for item in iterable:
if condition:
breakExample
for n in range(10):
if n == 3:
break
print(n)Key points
- Only exits the innermost loop, not outer ones
- Code after break in the same pass does not run
- Common for stopping a search once a match is found
- Skips the loop's else clause
- The usual way out of a while True: loop