A good way to debug code is to try walking through its execution with a simple example.
Let's try 4. We would expect to get the answer 4+3+2+1 = 10.
s(4)
- Before the loop starts,
a=3
, r=0
.
- After the first iteration,
a=2
, r=3
.
- After the second iteration,
a=1
, r=5
.
a != 1
is now False
, so the loop ends, and we return r
, which is 5
. We only ever added 3 and 2 to it, and forgot to add 4 and 1.
Looking at this a level higher, your function is always missing the first (n
) and the last (1
) values of the sum. Fix both of these mistakes and your function should work how you expect. These are both examples of the classic fencepost error - your fence is missing posts at both ends.