PythonMastery

break and continue in Python

continue skips the rest of one pass of a loop; break ends the whole loop. A short demo of each, then a practical example that uses both.

Two keywords change how a loop runs. continue skips the rest of the current pass and goes to the next item. break stops the loop completely.

The program

python
for i in range(10):
    if i == 3:
        continue  # skip 3 and go to the next number
    if i == 7:
        break     # stop the loop at 7
    print(i, end=" ")

print()
print("Loop finished")
output
0 1 2 4 5 6 
Loop finished

How it works

A practical example

Add up a list of readings, skipping missing values (None), and stop at the first negative value, which here marks the end of the data:

python
readings = [12, 15, None, 9, None, 20, -1, 30, 25]

total = 0
for value in readings:
    if value is None:
        continue
    if value < 0:
        break
    total += value

print(f"Total of valid readings: {total}")
output
Total of valid readings: 56

12 + 15 + 9 + 20 is 56. The two None values are skipped, and 30 and 25 are never read because the loop ended at -1.

In nested loops, break and continue affect only the innermost loop they are in.

Related programs: for else.

Learn the idea: Loops: for, while, and the Pythonic Patterns