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 = 0 inside 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.

  1. Start a variable total at 0.
  2. Loop over every day from 1 to days (including days) and add that day's coins to total.
  3. Print After 10 days: 55 coins using the variables (an f-string).