← Intro to programming with Python
Loop patterns: counting and adding up
Use a loop to keep a running total or a tally.
Most loops follow a few patterns, and two of the most useful are the running total and the counter. Both work the same way: make a variable BEFORE the loop (starting at 0), update it INSIDE the loop, and use the answer AFTER the loop. It is like a cashier adding each item to the bill, or a coach clicking a tally counter each time a runner passes.
total = 0
for n in range(1, 101):
total += n
print(total) # 5050
count = 0
for letter in "banana":
if letter == "a":
count += 1
print(count) # 3total collects every number from 1 to 100. count goes up only when the if is True.
Common mistake: setting total = 0 INSIDE the loop. Then it resets every time round, and you end up with only the last number.
Another common mistake: indenting the final print so it is inside the loop. It then prints every step instead of once at the end.