← All lessons

break: stop the loop

Sign in · Sign up

Lesson 3.3

break leaves the loop right now — the rest of this step and all the following steps are skipped:

for i in range(10):
    if i == 3:
        print("Found 3")
        break
    print(i)

The program prints 0, 1, 2, then Found 3 — and leaves the loop. The numbers 4, 5 and beyond never appear.

break is written inside a condition: without a condition the loop ends on its very first step. break outside a loop is an error.

Loop over the numbers from 1 to limit and print each one. As soon as you meet target, print Found <number> in an f-string and break out of the loop. limit and target are set by the check.

Hint

break leaves the loop at that very moment and goes no further.

The condition check goes inside if: as soon as the number equals target, print the message and break out of the loop. The loop goes from 1 to limit.