Coding

Break in Python: How the break Statement Works (Examples)

Break in Python ends the nearest enclosing for or while loop immediately and continues with the first line after it. Write break on its own line, usually inside an if, to stop looping as soon as you have what you were looking for.

names = ["ana", "bo", "cy", "dee"]

for name in names:
    if name.startswith("c"):
        print("found", name)
        break

print("done")

Example output:

found cy
done

The loop never looks at "dee". As soon as break runs, Python leaves the loop and prints done.

What break does, exactly

The Python language reference defines four behaviours, and everything else in this article follows from them:

  • break may only appear inside a for or while loop. It cannot appear in a function or class definition that is nested inside that loop.
  • It terminates the nearest enclosing loop only.
  • It skips the loop's optional else clause, if there is one.
  • If a for loop is ended by break, the loop variable keeps its current value.

The reference adds one more rule for try blocks, covered further down: a finally clause still runs before the loop is left.

Break in a for loop

The most common use is a search. You loop over items, and once you find a match there is no reason to check the rest. Stopping early saves work on long sequences and also makes the intent clear to the next reader.

numbers = [3, 8, 15, 22, 41]

first_even = None
for number in numbers:
    if number % 2 == 0:
        first_even = number
        break

print(first_even)

Example output:

8

Setting first_even = None before the loop matters. If no number matches, the loop runs to the end and the variable stays None, which you can test for afterwards.

Because the loop variable keeps its value after a break, you can also read it once the loop is over:

for i in range(10):
    if i == 4:
        break

print(i)

Example output:

4

Be careful with this when the loop finishes without a break: the variable then holds the last item, and if the sequence was empty it was never assigned at all. If you need to know which case happened, use the else clause described below.

Break in a while loop

A while loop checks its condition before each pass, so break is useful when the exit test belongs in the middle of the body, or when the condition is simply True. The loop below keeps squaring a counter until the result passes 50:

attempts = 0

while True:
    attempts += 1
    if attempts * attempts > 50:
        break

print(attempts)

Example output:

8

Seven squared is 49, which does not pass 50, and eight squared is 64, which does. The same pattern is common for reading input until the user types a quit word, or for retrying an operation until it succeeds.

while True with no reachable break never ends. If your program hangs, check that the if guarding the break can actually become true. Press Ctrl+C in the terminal to interrupt a runaway loop.

Break in nested loops

This is where most mistakes happen. A break leaves only the loop it is written in, so an outer loop keeps going.

for row in range(3):
    for col in range(3):
        if row * col == 2:
            print("found", row, col)
            break

Example output:

found 1 2
found 2 1

Both matches print because each break only ended the inner loop. If you wanted to stop at the first match, the outer loop needs to stop too. The cleanest way is to move the loops into a function and use return:

def find_pair():
    for row in range(3):
        for col in range(3):
            if row * col == 2:
                return row, col
    return None

print(find_pair())

Example output:

(1, 2)

return leaves every loop at once. If a separate function is awkward, the alternative is a flag variable: set found = True before the inner break, then add if found: break in the outer loop right after the inner one.

The rule that break cannot sit inside a function defined within the loop also matters here. A break in a nested def or lambda body cannot reach the loop around it, so Python rejects it.

Break with else: the for-else clause

A loop can have an else clause, which is easy to misread. It does not belong to an if. The tutorial puts it this way: if the loop finishes without executing a break, the else clause runs. If the loop is ended by break, the clause is skipped.

for n in [4, 6, 9]:
    if n % 2 == 1:
        print("odd number found:", n)
        break
else:
    print("all numbers are even")

Example output:

odd number found: 9

Change the list to [4, 6, 8] and no break happens, so the output becomes all numbers are even. In a for loop the else runs after the final iteration. In a while loop it runs when the condition becomes false. The tutorial notes that other ways of leaving a loop early, such as return or a raised exception, also skip it.

The tutorial's prime-number example is the standard demonstration. It searches for a factor of each number, and the else prints when none is found:

for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, 'equals', x, '*', n//x)
            break
    else:
        print(n, 'is a prime number')

Example output (as shown in the Python tutorial):

2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

Note that the else lines up with the inner for, not with the if. That indentation is the whole trick.

Break inside try and finally

When break leaves a try statement that has a finally clause, the finally block runs before the loop is actually left. Cleanup code is therefore not skipped:

for i in range(3):
    try:
        if i == 1:
            break
        print("body", i)
    finally:
        print("cleanup", i)

Example output:

body 0
cleanup 0
cleanup 1

On the second pass break fires, but cleanup 1 still prints before the loop ends. For more on try and finally, see Python exception handling with try and except.

Break, continue and pass compared

StatementEffectLoop continues?
breakLeaves the nearest enclosing loop and skips its elseNo
continueSkips the rest of this iteration and starts the nextYes
passDoes nothing; a placeholder where a statement is requiredYes, with the next line in the body

The articles on the continue statement and the pass statement cover the other two in detail. For a broader look at filtering inside loops, see Python for loop with an if condition.

If break does not behave as expected

  • The outer loop keeps running. The break is inside an inner loop. Use a function with return, or a flag, as shown above.
  • The else block runs when you expected it not to. The loop finished without hitting break, usually because the condition in the if was never true. Print the values being tested.
  • The else block never runs. A break fired. That is the intended behaviour.
  • The program hangs in while True. The if guarding the break never becomes true. Check that the variable it tests is actually updated in the loop body.
  • A syntax error mentioning break. Check the indentation: the statement must sit inside the loop body, and not inside a function or class defined within that loop. See IndentationError in Python if the indentation itself is wrong.

Frequently asked questions

What does break do in Python?
The break statement ends the nearest enclosing for or while loop right away. Python skips the rest of the loop body, skips any else clause attached to the loop, and continues with the first statement after the loop.
Can you use break outside a loop?
No. According to the Python language reference, break may only occur syntactically nested in a for or while loop, and not inside a function or class definition within that loop. Anywhere else it is a syntax error.
Does break exit all nested loops?
No. It only terminates the nearest enclosing loop. To leave several loops at once, put the loops in a function and use return, or set a flag and check it after the inner loop.
What is the difference between break and continue?
Break ends the whole loop. Continue ends only the current iteration and moves on to the next one. After a break, the code following the loop runs; after a continue, the loop keeps going.
Does the loop variable keep its value after break?
Yes. If a for loop is ended by break, the loop variable keeps the value it had at that moment, so you can read it after the loop.

Sources