Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion - Python, return value question

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 ?

like image 897
James Dwight Avatar asked Dec 14 '22 01:12

James Dwight


1 Answers

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.

like image 58
Khaled Alshaya Avatar answered Mar 02 '23 05:03

Khaled Alshaya