Running totals, explained simply
How would you add up the apples in five baskets? You start at zero in your head, then add each basket one by one. Programmers call this a running total, or an accumulator.
In Python you create a variable set to 0 before the loop. Inside the loop you add to it each time round. After the loop, the variable holds the total.
The same pattern counts things too: add 1 instead of adding a value. It is one of the most useful patterns in all of programming.
Example: Count the harvest
baskets = [4, 7, 2, 5]
total = 0
for apples in baskets:
total = total + apples
print(f"We picked {total} apples.")Output
We picked 18 apples.Try this
- Move total = 0 inside the loop. Why does the answer go wrong?
- Count how many baskets have more than 4 apples.
- Use total += apples, a shorter way to write the same line.
