Controlling Loops with break and continue

40 min read Loops in Depth

This is a free course. Log in to run the code exercises and track your progress.

Controlling Loops with break and continue

Two statements change the normal flow of a loop:

  • break leaves the loop at once. The statements after the loop run next.
  • continue skips the rest of the current pass and goes straight to the next one.
total = 0
while True:          # repeat until break
    n = int(input())
    if n == 0:
        break        # 0 means "no more numbers"
    if n < 0:
        continue     # ignore negative numbers
    total += n
print(total)

while True on its own would be an infinite loop; the break inside it is what ends it. This pattern is common when the program reads values until a special sentinel value, here 0, is typed.

Python exercise

Read integers, one per line, until 0 is read. Print the sum of the numbers that are not multiples of 3. Use break and continue.

total = 0
while True:
    n = int(input())
    if n == 0:
        break
    # skip multiples of 3 with continue
print(total)

Log in to edit and run this code.