1
I don’t understand how the code behaves after it leaves the recursive function on line 7, fat = n * fatorial(n-1)
, i.e., how the code assigns the value to the variable n
of this line and how is done the calculation of this 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)
In this reply i explain how a recursive function is executed for calculating factorial in Javascript. The logic is exactly the same and may be useful for you.
– Woss
Possible duplicate of Recursiveness in Python
– FReNeTiC