Python Fundamentals ยท Control Flow

break and continue

Skip one round with continue, or leave the loop early with break, on a list of sensor readings.

break_continue.py

readings = [4, -1, 7, 0, 9, 3]
total = 0

for r in readings:
    if r < 0:
        continue        # skip bad readings, go to the next one
    if r == 0:
        break           # 0 means the sensor stopped: leave the loop
    total = total + r

print("total", total)

Step by step

  1. Readings: -1 is a bad reading, 0 means the sensor stopped.
  2. total is created with the value 0.
  3. r is created with the value 4.
  4. Python checks r < 0 to decide which way the code goes.
  5. Python checks r == 0 to decide which way the code goes.
  6. A good reading: total becomes 4.
  7. r changes from 4 to -1.
  8. Python checks r < 0 to decide which way the code goes.
  9. -1 is negative: continue skips the rest of this round and jumps to the next reading.
  10. r changes from -1 to 7.
  11. Python checks r < 0 to decide which way the code goes.
  12. Python checks r == 0 to decide which way the code goes.
  13. total = 4 + 7 = 11.
  14. r changes from 7 to 0.
  15. Python checks r < 0 to decide which way the code goes.
  16. Python checks r == 0 to decide which way the code goes.
  17. The reading is 0: break leaves the loop completely.
  18. total is 11 (4 + 7): -1 was skipped by continue, and 9 and 3 were never reached because of break.