How to use break and continue

Stop with break

break immediately exits the nearest enclosing loop. It is useful when a search succeeds.

numbers = [4, 7, 12, 15]
for number in numbers:
    if number % 3 == 0:
        print('Found:', number)
        break

Skip with continue

continue skips the rest of the current iteration and starts the next one.

for number in range(1, 6):
    if number == 3:
        continue
    print(number)

Use else after a loop

A loop's else block runs only if the loop finishes without break. This can express unsuccessful searches cleanly.

target = 9
for value in [2, 4, 6]:
    if value == target:
        print('Found')
        break
else:
    print('Not found')

Avoid hiding loop logic

  • Use break when the stopping condition is clear near the top of the loop.
  • Use continue to reject invalid items before the main work.
  • Refactor deeply nested loops into functions when control flow becomes hard to follow.