python · level 1 · unit 6 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A for loop can visit every item in a list.
Think of a checkout. The cashier picks up each thing in your basket, one at a time, and beeps it. for coin in coins: does the same: each turn, coin holds the next item in the list.
No range needed. The loop runs once for every item, then stops by itself after the last one.
To add things up, keep a . Start a variable at 0 before the loop. Each turn, add the item to it. After the loop, it holds the full total.
coins = [2, 5, 1, 2]
total = 0
for coin in coins:
total = total + coin
print("Piggy bank:", total) Name the loop variable after one item: coin for coins, pet for pets.
guess first
What does this print, and how many times?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
daily_steps = [3000, 4000, 2000]
total = 0
for steps in daily_steps:
total = total + steps
print(total)
your turn
Your turn. Add up your shopping.
Type three prices in pounds, like 2 or 1.5. Then press run to see your total.
fix it
These scores should add up to 20. Can you fix the total?
- It prints 4, the last score. Which line is meant to add each score on?
- total = score throws away the old total and keeps only the newest score.
- Change it to total = total + score, so each score is added to what is already there.
nailed it
you added up a whole list in one go. :D
for item in my_list:visits every item in turn.- Start a running total at 0 before the loop.
- Add with
total = total + item, nottotal = item.
new words in your collection
- running total
This lesson isn’t saved. A free account remembers every lesson you finish.