Sum 1..n
1 到 n 求和
The accumulator pattern — initialize / update / return — appears in every Chapter 3 lesson and most of the rest of the course.
The problem
Implement sum_to_n(n) returning 1 + 2 + 3 + ... + n.
The autograder requires a for loop — no closed-form formula.
The accumulator pattern
Python · runnable
The + 1 gotcha
What goes wrong without it?
Why initialize before the loop?
Predict the output — then run.
Check yourself
sum_to_n(0) returns:
Now you try
Open 01-sum-to-n.py in WolfCode. The autograder runs 5 tests
including n = 0 and a check that you actually used a
for loop (not the closed-form formula).