Statement

break statement

break stops a for or while loop immediately and jumps to the first line after it, skipping the rest of the rounds.

BeginnerEvery example below runs in your browser. Change the code and press Run.

for item in iterable: if condition: break

break ends the loop it is in at once. Python jumps to the first line after the loop, even if there were more items left or the while condition is still true.

Use it when you were searching for something and found it, when a user types "quit", or to leave a while True: loop.

break only leaves the innermost loop. In nested loops, the outer loop keeps going. Also, a loop that ends with break skips its else block, which is a neat way to say "not found".

Examples

1Stop at the first match

Pythoneditable
names = ["Ines", "Tom", "Priya", "Tom"]
for i, name in enumerate(names):
    if name == "Tom":
        print("Found Tom at position", i)
        break
Output
Found Tom at position 1

The second "Tom" is never reached.

2Leave while True at a stop word

The list stands in for what a user types. Everything after "done" is ignored.

Pythoneditable
typed = ["2.5", "5", "done", "9"]
total = 0
i = 0
while True:
    text = typed[i]
    i += 1
    if text == "done":
        break
    total += float(text)
print("Total:", total)
Output
Total: 7.5

3break with for ... else

The else block runs only when the loop finishes without hitting break.

Pythoneditable
emails = ["[email protected]", "[email protected]"]
for email in emails:
    if "@" not in email:
        print("Bad email:", email)
        break
else:
    print("All emails look fine")
Output
All emails look fine

4break only leaves the inner loop

Pythoneditable
for row in range(3):
    for col in range(3):
        if col == 2:
            break
        print(row, col)
Output
0 0
0 1
1 0
1 1
2 0
2 1

Common mistakes

Expecting break to leave all nested loops

break only ends the loop it is directly inside. To stop everything, put the loops in a function and use return statement, or set a flag and check it in the outer loop.

Pythoneditable
def find(grid, target):
    for r, row in enumerate(grid):
        for c, value in enumerate(row):
            if value == target:
                return r, c
    return None

print(find([[1, 2], [3, 4]], 3))
Output
(1, 0)

Using break outside a loop

break is only allowed inside for or while. Used in an if that is not in a loop, it is a SyntaxError. To leave a function early, use return.

Questions people ask

What is the difference between break and continue?

break ends the whole loop. continue statement only skips the rest of the current round and moves on to the next one.

How do I break out of two loops at once?

Move the loops into a function and return from it. That is the clearest way in Python.

Does break work in an if statement?

Only when that if is inside a loop. break always acts on the nearest enclosing loop.

Spotted a mistake on this page? Tell us