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
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:
sales = [3, 6, 12, 2]
total = 0
for sale in sales:
total = total + sale
print(f"Day's sales: ${total}")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.
The same pattern counts things. Add 1 instead of the item. += is a shortcut that means "add this to the variable":
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)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.
The variable that changes can be a size. Each trip paints a ring, then makes size bigger for the next one:
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")
size started at 14 and grew by 26 on every trip. Paint first, then grow. That order makes sure the smallest ring gets painted.
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.