Skip one round with continue, or leave the loop early with break, on a list of sensor readings.
Python · beginner · 6 min · 18 steps · free
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)total is created with the value 0.r is created with the value 4.r < 0 to decide which way the code goes.r == 0 to decide which way the code goes.r changes from 4 to -1.r < 0 to decide which way the code goes.continue skips the rest of this round and jumps to the next reading.r changes from -1 to 7.r < 0 to decide which way the code goes.r == 0 to decide which way the code goes.r changes from 7 to 0.r < 0 to decide which way the code goes.r == 0 to decide which way the code goes.break leaves the loop completely.for x in [1,2,3]: if x == 2: continue; print(x), what is printed?Answer: 1 and 3. Only 2 is skipped.
for x in [1,2,3]: if x == 2: break; print(x), what is printed?Answer: 1. The loop stops at 2.
← for Loops, range and enumerate · Nested Loops →