CurriculumPython for Loops and range() for KidsBuilding up a total
How to Build a Running Total with a Python for Loop
Carrying a value forward, loop pass after loop pass.
Building up a total
So far your loops repeated something. Now let's make a loop that BUILDS something up, one pass at a time.
gold = gold + 10, written INSIDE a loop, adds 10 every single time it runs.
gold = 0
for i in range(3):
gold = gold + 10
print(gold)Output
10
20
30Each pass starts from wherever the LAST pass left off. That's the whole trick — the value carries forward.
gold = 0
for i in range(3):
gold = gold + 10
print(gold)If you only want the FINAL total, move print() outside the loop — so it runs once, after all the passes finish.
gold = 0
for i in range(3):
gold = gold + 10
print(gold)Output
30Notice the indent difference. Inside the loop = every pass. Outside the loop = just once, at the end.
Check your understanding
gold = 0. This loop runs 3 times, adding 10 each time. Where does print(gold) go to show ONLY the final total?
gold = 0
for i in range(3):
gold = gold + 10
???Why: Indented under the for, a line runs every pass. Un-indented, back at the loop's own level, it runs once — after the loop is completely finished. That's how you get one final number instead of three.
What you'll practice
The dragon finds 10 gold coins on each of 3 trips. Keep a running total and print the total after each trip — not just the final number.
More from this topic
Building up a total is one lesson inside Python for Loops and range() for Kids — see the full lesson order and what the whole topic covers.
View the full topic →