Write a function that sums every integer from 1 up to and including n.
sum_to_n(n)
sum_to_n(5) // → 15 (1+2+3+4+5)
sum_to_n(1) // → 1
sum_to_n(10) // → 55
sum_to_n(0) // → 0 (nothing to sum)
This is the accumulator pattern from the lesson, applied directly.
def sum_to_n(n):
total = 0
for i in range(1, n + 1):
total += i
return total
total = 0 starts the running sum outside the loop — it needs to exist before the loop begins, and it needs to start at 0 (the "identity" value for addition — adding 0 to anything doesn't change it).
range(1, n + 1) is worth double-checking: since range(start, stop) always stops before stop, range(1, n) would only go up to n - 1, missing n itself. Adding 1 to the stop value (n + 1) is what makes the range actually include n.
For n = 0, range(1, 1) produces no numbers at all — the loop body never runs, and total stays 0, which is exactly the right answer (there's nothing between 1 and 0 to sum).
def sum_to_n(n):
total = 0
for i in range(1, n + 1):
total += i
return total
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.