← back to unit
Medium
# basics loops
The Accumulator Pattern
One of the most useful loop patterns: start a variable at 0, then add to it every time through the loop, building up a total:
total = 0
for i in range(1, 6):
total += i
print(total)
prints 15 (that's 1 + 2 + 3 + 4 + 5).
Your turn: read a number n. Compute and print the sum of every whole number from 1 to n (inclusive).
💡 need a hint?
pyb-loop-accumulator.py🔒 given lines are locked — write your code in between
loading...