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
- When
iis 3,continuejumps back to the top of the loop, soprint(i)does not run for 3. - When
iis 7,breakends the loop. The numbers 7, 8 and 9 are never printed. - After
break, Python continues with the first line after the loop. Here that isprint(), which ends the line of numbers, and thenLoop finishedis printed.
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.