How does this recursive function (factorial function) in Python behave?

1

I do not understand how the code behaves after it exits the recursive function on line 7, fat = n * fatorial(n-1) , that is, how the code assigns the value to the variable n of that line and how to calculate that line where the code assigns its value to the variable fat ?

Note: I am self-taught.

#!/usr/bin/python

def fatorial(n):                             #linha1
    print("Calculando o fatorial de %d" % n) #linha2
    if n==0 or n == 1:                       #linha3
        print("Fatorial de %d = 1" % n)      #linha4
        return 1                             #linha5
    else:                                    #linha6
        fat = n * fatorial(n-1)              #linha7
        print(" fatorial de %d = %d" % (n, fat) ) #linha8
    return fat                              #linha9

fatorial(4)
    
asked by anonymous 31.05.2017 / 17:42

1 answer

1

It's a little complex to explain but I'll try.

  • The factorial function (4) is called:
  • The factorial execution (4) "hangs" when it needs to compute fatorial(4-1) ;
  • A new call is made to the fatorial function in another scope with the value of n being 3 . This new call "hangs" in the same place because it is now necessary to calculate the value of fatorial(2) . This happens until the execution flow arrives at the point of calculating the fatorial(1) , which returns the value 1.
  • Now the FRAME of the fatorial(2) function gets the return value to replace fatorial(2-1) and execution continues.
  • The print statement is executed and the variable returned is now fat with the value of 2 .
  • When the fatorial(2) function was executed, the returned value was 2 .
  • This value will be replaced in the frame of fatorial(3) in line 7, and so on.

To understand how this function works you need to be aware of variable scope and function frames.

Try to access this site here, it will help you understand: link

    
31.05.2017 / 18:11