break

For Loops

break

In this tutorial, we'll stop a loop early.

break stops a loop immediately.

names = ["Ada", "Grace", "Linus"]

for name in names:
    if name == "Grace":
        print("Found Grace")
        break

Once Python reaches break, the loop ends.

Why break Is Useful

Use break when there is no reason to keep looping.

Example: searching for the first matching item.

numbers = [3, 7, 10, 12]

for number in numbers:
    if number % 2 == 0:
        print("First even number:", number)
        break

Output:

First even number: 10

The loop does not continue to 12.

break Only Stops One Loop

If loops are nested, break stops the inner loop it is inside. It does not automatically stop every loop.

Searching With a Flag

Sometimes you want to remember whether you found something:

numbers = [1, 3, 5, 8]
found_even = False

for number in numbers:
    if number % 2 == 0:
        found_even = True
        break

print(found_even)

The loop stops once the first even number is found.

Common Mistake

Do not use break when you actually want to process every item:

for score in scores:
    print(score)
    break

This prints only the first score.

Practice

Loop over a list of passwords and stop when you find "secret123".