Sum and Count with a Python for Loop
Add Up Numbers with a Running Total
To add up numbers in a for loop, keep a running total: a variable that starts at 0 and grows by each item with += (chapter 5). This is called the accumulator pattern ("accumulate" means "collect bit by bit").
prices = [40, 25, 60]
total = 0
for price in prices:
total += price
print("Total:", total)Total: 125
Think of it like a shop's cash register: it starts at 0, and every item the cashier scans is added to the amount on the screen.
The three steps
- Before the loop: start the total at
0. - Inside the loop: add the current item,
total += price. - After the loop: use the result, here
print().
Watch the total grow by printing it inside the loop:
total = 0
for price in [40, 25, 60]:
total += price
print("so far:", total)so far: 40 so far: 65 so far: 125
Add up input
With range() and input() from the last topic, you can add numbers the user types:
total = 0
for i in range(3):
total += int(input())
print("Total:", total)Total: 35
For a list you already have, sum(prices) from chapter 9 gives the same answer in one go. The loop shines when the numbers arrive one at a time, or when you only want to add some of them (next lesson).
Common mistakes
- Forgetting
total = 0: Python stops with aNameError, becausetotal += priceneeds a value to add to. - Putting
total = 0inside the loop: the total is reset every time and ends up as the last price only.
Start at 0 before the loop, add with += inside it, use the total after it.