ZetCode

Python break statement

last modified November 29, 2026 Python 3.15

In this article we show how to use the break statement to leave a loop early.

The break statement ends the nearest enclosing for or while loop. Execution continues with the first statement after the loop; the rest of the loop body and all remaining iterations are skipped. A loop usually stops when its condition becomes false or when its data is exhausted. With break, the loop can also stop as soon as the answer is known: a value is found, an error appears, or a task succeeds.

The Python control flow article introduces break together with the other loop statements. This article looks at it in more detail. Its counterpart, which skips only one iteration, is covered in Python continue keyword.

Leaving a while loop

The while True loop has no condition that ever becomes false. It runs until a break statement ends it. This form is useful when the stop condition is easier to test in the middle of the loop than at its top.

first_multiple.py
n = 100

while True:
    n += 1
    if n % 7 == 0:
        break

print("first multiple of 7 above 100:", n)

The loop increases n and tests it. When the number is divisible by seven, break ends the loop and the program prints the result.

$ python first_multiple.py
first multiple of 7 above 100: 105

Leaving a for loop

A for loop ends when it has gone through all items. With break, it can stop at the first item that matters.

first_negative.py
readings = [12.5, 14.1, 13.8, -2.0, 15.2, -1.4]

for i, value in enumerate(readings):
    if value < 0:
        print(f"invalid reading {value} at index {i}")
        break
    print(f"reading {value} is valid")

print("done")

The readings are checked one by one. The first negative value is reported and the loop stops; the readings after it are never examined. Without the break, the program would continue with 15.2 and report -1.4 as well.

$ python first_negative.py
reading 12.5 is valid
reading 14.1 is valid
reading 13.8 is valid
invalid reading -2.0 at index 3
done

What break skips

The break statement transfers control out of the loop immediately. Three things are skipped: the rest of the loop body, the remaining iterations, and the else clause of the loop.

skipped.py
for word in ["red", "green", "stop", "blue"]:
    print("checking", word)
    if word == "stop":
        break
        print("this line never runs")
    print("accepted", word)
else:
    print("the loop ran to the end")

print("after the loop")

The word stop triggers the break. The print statement right after it is unreachable, the accepted line does not run for stop, and the word blue is never checked. The else clause runs only when the loop finishes without break, so it is skipped too. The code after the loop runs normally.

$ python skipped.py
checking red
accepted red
checking green
accepted green
checking stop
after the loop

The else clause and searching

The else clause of a loop pairs naturally with break. In a search, break means the item was found and else means the loop went through everything without finding it. No extra flag variable is needed.

for_else.py
users = ["anna", "boris", "cyril"]

for name in ["boris", "david"]:
    for user in users:
        if user == name:
            print(f"{name}: found")
            break
    else:
        print(f"{name}: not found")

For each name, the inner loop searches the list of users. When it finds the name, it prints a message and breaks, which also skips the else clause. When the inner loop ends on its own, the else clause reports that the name is missing.

$ python for_else.py
boris: found
david: not found

Retrying an operation

The else clause works with while loops as well. It runs when the loop condition becomes false, but not when the loop is left with break. This fits a retry loop with a limited number of attempts.

retries.py
responses = ["timeout", "timeout", "ok", "timeout"]

attempt = 0
while attempt < 5:
    status = responses[attempt]
    attempt += 1
    print(f"attempt {attempt}: {status}")
    if status == "ok":
        break
else:
    print("giving up")

print("attempts used:", attempt)

The list simulates the results of a network call. The loop tries at most five times and breaks on the first success. If all attempts failed, the condition attempt < 5 would become false and the else clause would print giving up. Here the third attempt succeeds, so the else clause is skipped.

$ python retries.py
attempt 1: timeout
attempt 2: timeout
attempt 3: ok
attempts used: 3

Nested loops

A break statement ends only the innermost loop that contains it. The outer loop continues with its next iteration.

nested.py
grid = [
    [3, 8, 1],
    [9, 0, 4],
    [7, 0, 2],
]

for row in grid:
    for value in row:
        if value == 0:
            print("zero, leaving the inner loop")
            break
        print(value, end=" ")
    print("| next row")

The inner loop prints the values of a row and stops at the first zero. The outer loop is not affected: it moves on to the next row and starts a new inner loop. The second and the third rows are cut short at their zeros.

$ python nested.py
3 8 1 | next row
9 zero, leaving the inner loop
| next row
7 zero, leaving the inner loop
| next row

Leaving nested loops with a flag

Python has no labelled break that leaves several loops at once. A common solution is a variable that the inner loop sets before it breaks and that the outer loop checks after the inner loop.

flag.py
grid = [
    [3, 8, 1],
    [9, 0, 4],
    [7, 0, 2],
]

found = None

for r, row in enumerate(grid):
    for c, value in enumerate(row):
        if value == 0:
            found = (r, c)
            break
    if found:
        break

print("first zero at", found)

The inner loop stores the position of the zero in found and breaks. Right after the inner loop, the outer loop sees that found is set and breaks as well. The zero in the last row is never reached. Another common solution is to move the loops into a function and leave both with return.

$ python flag.py
first zero at (1, 1)

Leaving nested loops with else and continue

The else clause offers a way to leave nested loops without a flag. The outer loop breaks only if the inner loop was broken.

else_continue.py
grid = [
    [3, 8, 1],
    [9, 0, 4],
    [7, 0, 2],
]

for r, row in enumerate(grid):
    for c, value in enumerate(row):
        if value == 0:
            break
    else:
        continue
    break

print(f"first zero at ({r}, {c})")

When the inner loop finishes without finding a zero, its else clause runs continue, and the outer loop goes on with the next row. When the inner loop breaks, the else clause is skipped and the outer break runs. The loop variables r and c keep their last values after the loops, so they hold the position of the zero. The idiom is compact but harder to read than a flag; use it with a comment in real code.

$ python else_continue.py
first zero at (1, 1)

break and finally

When break leaves a try block, the finally clause still runs before the loop ends. Cleanup code in finally is never skipped.

finally_runs.py
tasks = ["parse", "fail", "save"]

for task in tasks:
    try:
        print("start", task)
        if task == "fail":
            print("stopping the batch")
            break
        print("finish", task)
    finally:
        print("cleanup after", task)

print("batch ended")

The fail task triggers the break. Before control leaves the loop, Python runs the finally clause of the current iteration, so cleanup after fail is printed. The save task is never started.

$ python finally_runs.py
start parse
finish parse
cleanup after parse
start fail
stopping the batch
cleanup after fail
batch ended

break inside finally

The opposite case, a break placed inside a finally clause, is a known trap. If an exception is being raised, the break discards it silently. Since Python 3.14 (PEP 765), the compiler emits a SyntaxWarning for break, continue, and return that leave a finally block.

finally_warning.py
for n in range(3):
    try:
        print("dividing by", n)
        result = 10 / n
    finally:
        break

print("the loop ended without an error")

In the first iteration, 10 / 0 raises ZeroDivisionError. Before the exception leaves the loop, the finally clause runs, and its break ends the loop and discards the exception. The program continues as if nothing had happened. The warning is printed when the file is compiled, before the program runs. Move the break out of the finally clause to fix such code.

$ python finally_warning.py
/home/user/break-keyword/finally_warning.py:6: SyntaxWarning: 'break' in a 'finally' block
  break
dividing by 0
the loop ended without an error

break outside a loop

The break statement is valid only inside a loop. It cannot end an if block, and it cannot leave a loop from inside a function that the loop calls. Such code is rejected when the file is compiled.

outside.py
count = 0

if count == 0:
    print("nothing to do")
    break

The break is placed in an if block that is not inside any loop. Python reports a SyntaxError and runs no code from the file; even the first print statement does not run.

$ python outside.py
  File "/home/user/break-keyword/outside.py", line 5
    break
    ^^^^^
SyntaxError: 'break' outside loop

Source

The break statement, break and continue statements in the Python tutorial, PEP 765 – Disallow return/break/continue that exit a finally block

In this article we have used the break statement to leave while and for loops early, combined it with the else clause of loops, left nested loops with a flag and with the else/continue idiom, and seen how it interacts with try/finally. See also Python continue keyword, Python control flow, and Python for loop.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.