Learning LibraryCore Coding LibraryKids

Running totals and counters: build an answer bit by bit

A loop can do more than repeat. It can build something up as it goes: a total that grows with every sale, or a ring that gets bigger each time around.

The big idea

Start a variable before the loop, then change it a little on every trip. When the loop ends, the variable holds the finished answer.

See it in code

1Start simple

This is the register. total starts at zero, once, above the loop. Inside the loop, each sale is added on top of what's already there:

python
sales = [3, 6, 12, 2]

total = 0
for sale in sales:
    total = total + sale
print(f"Day's sales: ${total}")
Adding up a morning of sales:
Day's sales: $23

The total went 3, then 9, then 21, then 23. The last line isn't pushed in, so it shows only the finished total.

2A step further

The same pattern counts things. Add 1 instead of the item. += is a shortcut that means "add this to the variable":

python
sales = [3, 6, 12, 2, 12, 5]
big_sale = 10

count = 0
big_count = 0
biggest = 0
for sale in sales:
    count += 1
    if sale >= big_sale:
        big_count += 1
    if sale > biggest:
        biggest = sale
print("Number of sales:", count)
print("Big sales:", big_count)
print("Biggest sale: $", biggest)
A counter, a picky counter, and a best-so-far:
Number of sales: 6
Big sales: 2
Biggest sale: $ 12

count grew on every trip. big_count grew only when its check was true. And biggest was replaced whenever a bigger sale came along.

3In the paint studio

The variable that changes can be a size. Each trip paints a ring, then makes size bigger for the next one:

python
ring_count = 7
size = 14
grow = 26

paper("midnight blue")
for count in range(ring_count):
    ring(x=200, y=170, size=size, color="orange red", width=2)
    size += grow
rect(x=200, y=375, width=400, height=50, color="black")
A peony firework, grown by a loop:
A peony firework made of seven thin orange-red rings growing outward from one point in a midnight-blue sky above a black harbor.

size started at 14 and grew by 26 on every trip. Paint first, then grow. That order makes sure the smallest ring gets painted.

The same idea, everywhere

Games are full of these. A score climbs by ten for each brick. Lives count down by one. A falling cupcake's y grows a little on every frame.

Try it yourself

In the peony, move size = 14 to just inside the loop, above the ring line, and run it. Where did the rings go? Put it back, and explain what happened.

The common mistake

Starting the variable inside the loop. If total = 0 sits under the for line, the total is wiped on every trip. A starting value goes before the loop, once.

What it unlocks

Running totals live inside for loops and while loops. They're made of plain math on a variable, done again and again.

Older, or want more depth? Read the Teens version →