This Python 3 function should sum the integers from 1 through n, inclusive. Assume n is a nonnegative integer. Why does sum_to(5) give 10 instead of 15? Show a minimal fix and proposed tests.
The upper bound of range is excluded. Use range(1, n + 1) to include n.
- Compare the goal with the loop
For n = 5, range(5) visits 0, 1, 2, 3 and 4. Their sum is 10. The intended values are 1 through 5.
- Correct the bounds
Start at 1 and stop just after n. Keep the accumulator and return structure unchanged.
- Propose boundary and normal tests
Under the stated input assumption, predict sum_to(0) = 0, sum_to(1) = 1 and sum_to(5) = 15. These test the empty range, one value and several values.
Trace the corrected n = 5 loop: total becomes 1, 3, 6, 10, 15. These are predicted values, not a claim that this website ran the code.