Skip to main content
🐍 Python Basics 🐍

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:

  1. Start a total at 0.
  2. for each number from 1 to n, add it to total.
  3. 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.