Skip to content

Leaving a loop with break and continue

~15 min ยท prerequisite: Repeating with for and range

What you will be able to do

  • Use break to leave a loop right away, and continue with the code after the loop.
  • Use continue to skip the rest of one round and start the next round.
  • Use while True together with break for a loop that stops when a condition is met inside the block.

The idea

A break statement is the single word break on its own line inside a loop. When Python runs it, the loop ends immediately. Any lines left in the block are skipped, and Python continues with the first line after the loop.

A continue statement is the word continue on its own line. When Python runs it, the rest of the current round is skipped, and the loop moves on to the next round. In a for loop, that means the next value from the range. In a while loop, Python goes back to check the condition.

Both words affect the loop that directly contains them. Each statement must sit inside a loop.

A common pattern is while True:. The condition is always True, so the loop would never end by itself. A break inside the block is the only way out. This is useful when you cannot know in advance how many rounds you need.

Worked example

found = -1
for number in range(1, 20):
    if number * number > 50:
        found = number
        break
print("First square over 50 comes from", found)

Line by line, this is what Python does:

  1. found = -1 stores a value that means "not found yet".
  2. The loop tries number values 1, 2, 3, and so on.
  3. For number equal to 1 through 7, the if condition is False, because the squares are 49 or less.
  4. For number equal to 8, 8 * 8 is 64, which is greater than 50. The condition is True, so found becomes 8.
  5. break ends the loop at once. The values 9 and beyond are never checked.
  6. print shows the value of found.

The output is First square over 50 comes from 8.

Now a continue example. It adds only the odd numbers from 1 to 7.

total = 0
for number in range(1, 8):
    if number % 2 == 0:
        continue
    total += number
print(total)

When number is even, continue skips the total += number line. The output is 16, which is 1 + 3 + 5 + 7.

Try it

Each block checks its result with assert.

first_over = -1
for n in range(1, 100):
    if n * 3 > 20:
        first_over = n
        break
assert first_over == 7

checked = 0
for i in range(5):
    if i == 2:
        break
    checked += 1
assert checked == 2
assert i == 2
n = 0
count = 0
while n < 10:
    n += 1
    if n % 3 != 0:
        continue
    count += 1
assert count == 3
attempts = 0
while True:
    attempts += 1
    if attempts * attempts >= 30:
        break
assert attempts == 6

In the second block, n += 1 comes before the continue, so n always changes. That is what lets the loop finish.

Common mistakes

  1. Putting the counter update after continue. The following loop never ends:

    n = 0
    while n < 3:  # never ends, do not run
        if n == 1:
            continue
        n += 1
    

    When n is 1, continue jumps back to the condition before n += 1 runs, so n stays 1 forever. Update the counter before the continue, as the try-it block did.

  2. Using break outside a loop. Writing break inside an if that is not inside a loop gives:

    SyntaxError: 'break' outside loop
    

    Only a for or while loop can contain break.

  3. Using break when you meant continue. The following check fails:

    total = 0
    for n in range(1, 6):
        if n == 3:
            break
        total += n
    assert total == 15
    
    AssertionError
    

    break stops the whole loop when n is 3, so total is only 1 + 2, which is 3. Use continue to skip just that round.

  4. Writing continue outside a loop. Writing continue at the top level of a program gives:

    SyntaxError: 'continue' not properly in loop
    

    Like break, continue needs a loop around it.

Practice

  1. Use a for loop over range(1, 50) with break to find the first number greater than 20 that is divisible by 7. Assert that the result is 21.
  2. Use a for loop over range(10) and continue to skip the even numbers. Count the odd numbers and assert that the count is 5.
  3. Use while True with a counter to find the smallest n for which n * n * n is greater than 500. Assert that n is 8.
  4. Use a for loop over range(1, 21) to add the numbers 1 through 20, but skip any multiple of 5 with continue. Assert that the total is 160.
  5. Stretch: use while True with a counter n that starts at 0. Each round, add 1 to n. If n is greater than 10, use break. If n is a multiple of 3, use continue. Otherwise add n to total. Assert that total is 37.
Solution
  1. python result = -1 for n in range(1, 50): if n > 20 and n % 7 == 0: result = n break assert result == 21

  2. python count = 0 for i in range(10): if i % 2 == 0: continue count += 1 assert count == 5

  3. python n = 0 while True: n += 1 if n * n * n > 500: break assert n == 8

The value 7 gives 343, which is too small, and 8 gives 512.

  1. python total = 0 for n in range(1, 21): if n % 5 == 0: continue total += n assert total == 160

  2. python n = 0 total = 0 while True: n += 1 if n > 10: break if n % 3 == 0: continue total += n assert total == 37

The numbers 1 to 10 add up to 55. Removing 3, 6, and 9 leaves 37.

Recap

  • break ends the loop that contains it right away, and the program continues after the loop.
  • continue skips the rest of the current round and starts the next round.
  • In a while loop, update the counter before any continue, or the loop may never end.

Sources