RECURSION basic code

Can somebody please breakdown why this code outputs 30 ?
( sorry about the formatting, please enlighten me)

def addchain(number, increment):
    if number <= 0:
        return 0
    else:
        return number + addchain(number - increment, increment)
       
print(addchain(10,2))
def addchain(number, increment):
    if number <= 0:
        return 0
    else:
        return number + addchain(number - increment, increment)

print(addchain(10,2))
# output per loop.
# 10 + 8 + 6 + 4 + 2 + 0 = 30

it is 30 because of the numbers above in comment :slight_smile:

also, to do code blocks you want to have 3x ` and then a new line, your code, new line and then 3 more to close the block :slight_smile:

1 Like

Thanks for that, I kind of get it. . Im also wondering about the second return statement, under else:.
It was always my understanding that a return statement immediately ends the loop,
so after the first iteration, shouldn’t the loop have ended ? returning 10 not 30 .
Here’s the code again:
`def addchain(number, increment):
if number <= 0:
return 0
else:
return number + addchain(number - increment, increment)
print(addchain(10,2))’

Only if the number is less than or equal to 0. Which the first loop isn’t. So it goes to the else which then calls it again with 8 (10-2)
This then still isn’t less than or equal to 0 so it also goes to else…etc etc till it does hit 0 which then returns all the numbers which get added up

Thanks for that. Ok, so could you define for me what the exact function of a return statement is ?
and where does exactly the values get returned to, if there is no variable assigned to it ?