
Code
Count the Coins
A super common loop pattern is the accumulator: start a total at zero, then add to it each time around the loop.
total = 0
for price in range(1, 4):
total = total + price
print(total) # 1 + 2 + 3 = 6
total = total + price means "take the old total, add price, and
store the result back in total". Python has a shortcut that does
exactly the same thing:
total += price
There are matching shortcuts -=, *= and /= too.
Pip tip: Create the total before the loop. If you put
total = 0inside the loop, it gets reset to zero every time!
Assignment
Pip finds coins on a beach: 1 coin on day 1, 2 coins on day 2, 3 on day 3, and so on.
- Start a variable
totalat0. - Loop over every day from
1todays(includingdays) and add that day's coins tototal. - Print
After 10 days: 55 coinsusing the variables (an f-string).
Pip finds coins on a beach: 1 coin on day 1, 2 coins on day 2, 3 on day 3, and so on.
- Start a variable
totalat0. - Loop over every day from
1todays(includingdays) and add that day's coins tototal. - Print
After 10 days: 55 coinsusing the variables (an f-string).
main.py Python sleeping
Press Run to try your code, then Check to test it.