The Summation
At the top of the stairs, Hoppy finds scattered orbs of light. He needs to collect them all to power the next portal.
We can use a loop to add up numbers. This is called the Accumulator Pattern.
The Accumulator
Imagine a basket. Before you start collecting, the basket is empty (total = 0).
Each time you find an item, you put it in the basket (total = total + item).
gold = 0 # Empty basket
for coin in range(3):
gold = gold + coin # Add current coin to basket
print("Collected coin:", coin)
print("Total gold:", gold)
First, gold is 0. Then 0+0=0. Then 0+1=1. Then 1+2=3. The final total is 3.
Your Mission
Create a variable named energy and set it to 0.
Write a for loop that runs 5 times (using range(5)).
Inside the loop, add the loop variable i to energy.
(Hint: energy = energy + i)
Outside the loop (no indentation), print energy.
If you print inside the loop, you see the running total. If you print outside, you only see the final result.
Suggested SolutionClick to expandClick to collapse
Here is how to gather the energy:
energy = 0 for i in range(5): energy = energy + i print(energy)
Advanced TipsWant more? Click to expandClick to collapse
Programmers are lazy. Instead of energy = energy + i, we often write energy += i.
It means exactly the same thing: "Add i to energy and save the result."