We'd like the following to be true when there is at least one argument:
add(x1, x2, ..., xn) == x1 + add(x2, ..., xn)
Eventually, though, we reach this case:
add(x1) == x1 + add()
What should add
return with no arguments? Since add(x1)
should clearly equal x1
, we have to define add() == 0
. This is because 0 is the identity for addition: x + 0 == x
for any value of x
.
Since your loop won't be entered at all when there are no arguments, we need to initialize sum = 0
so that after we skip the loop, return sum
will return 0
as required.
The loop itself is just adding numbers one after the other. If args
is 1,2,3,4 then the function is equivalent to
sum = 0
sum += 1 # 0 + 1 == 1
sum += 2 # 1 + 2 == 3
sum += 3 # 3 + 3 == 6
sum += 4 # 6 + 4 == 10
return sum # return 10