break, continue & Accumulators
beginner12 min readLesson 22 of 169
Leaving early, skipping rounds, and the sum/count/best patterns.
break: leave early
for n in [3, 7, 0, 9]:
if n == 0:
break # stop the whole loop now
print(n) # 3, 7
continue: skip this round
for n in range(6):
if n % 2 == 0:
continue # jump to the next round
print(n) # 1, 3, 5
Accumulator patterns โ the bread and butter
Most real loops update a running result:
total = 0
for price in [5, 8, 12]:
total += price # summing
print(total) # 25
hits = 0
for n in [1, 7, 4, 9]:
if n > 5:
hits += 1 # counting matches
print(hits) # 2
biggest = None
for n in [1, 7, 4]:
if biggest is None or n > biggest:
biggest = n # tracking a maximum
print(biggest) # 7
Three shapes to memorize through practice: sum, count, best-so-far. Every data report you will ever write is built from these.