🐸

The Summation

Python Basicspython-basics-19-the-summation
Reward: 90 XP
|

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

1
The Basket

Create a variable named energy and set it to 0.

2
The Search

Write a for loop that runs 5 times (using range(5)).

3
Collect

Inside the loop, add the loop variable i to energy. (Hint: energy = energy + i)

4
Result

Outside the loop (no indentation), print energy.

Inside or Outside?

If you print inside the loop, you see the running total. If you print outside, you only see the final result.

Suggested Solution
Click to expand

Here is how to gather the energy:

energy = 0
for i in range(5):
  energy = energy + i
print(energy)
Advanced Tips
Want more? Click to expand

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."

pymain.py
Loading...
Terminal
Terminal
Ready to run...