Add Them Up with a Loop π
Now you write a loop! You'll add up all the numbers from 1 to n.
The plan is always the same three steps:
- Start a
totalat0. foreach number from1ton, add it tototal.return total.
total = 0
for i in range(1, n + 1):
total = total + i
return total
We use range(1, n + 1) so the last number n is included.
Your task
Write sum_to(n) that returns the sum of all integers from 1 to n
inclusive. sum_to(5) is 1 + 2 + 3 + 4 + 5 = 15.
β‘ 35 XP
π§± Code blocks
Drag a block into the editor, or tap it to drop it in where your cursor is. Add them in order to build your answer.
solution.pyRuns in your browser (Pyodide)
Loading editorβ¦
Tests3 to pass
sum_to(5) == 15
sum_to(1) == 1
sum_to(10) == 55
Run your code to check these.