I realize that this may sound like a silly question, but the last time I programmed it was in assembler so my thinking may be off:
A recursive function as so:
def fac(n):
if n == 0:
return 1
else:
return n * fac(n - 1)
Why is it that when the function reaches n == 0 that it does not return 1 but rather the answer which is the factorial. I am thinking something like in assembler it would be when n == 0:
mov eax, 1
ret
Why does the code above work, I suppose python returns the last value on the stack before that condition ?
Think about like this, for fac(5)
for example:
return 5 * fac(4)
return 4 * fac(3)
return 3 * fac(2)
return 2 * fac(1)
return 1 * fac(0)
1
So 1
will be the first returned value but it will be returned to fac(1)
and fac(1)
will be returned to fac(2)
and so on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With