johnny k
johnny k

Reputation: 37

Can't understand recursion in function

I can't understand how it works. Why the output has the first line, where var X == 1 ? And, how compiler doesn't give an error if new_var is not defined anywhere as a integer ?
Is it because of call stack works like that ? It returns from the last call, so after returning 1, new_val becomes == 1 ?!

Output:
I'm here!!!! X is: 1
I'm here!!!! X is: 2, and new_var is 1
I'm here!!!! X is: 3, and new_var is 2
I'm here!!!! X is: 4, and new_var is 6
24

def fact_rec(x):
    if x > 0:         
        if x == 1:
            print(f"I'm here!!!!  X is: {x}")
            return 1
        else:            
            new_var = fact_rec(x-1)
            print(f"I'm here!!!!  X is: {x}, and new_var is {new_var}")
            return new_var*x
    else:
        return "It's negative"
print(fact_rec(4))

Upvotes: 0

Views: 59

Answers (1)

booyaakaashaa
booyaakaashaa

Reputation: 177

for, fact_rec(4) The function will check if 4 is greater than zero or not, it is here. Then it will check if it is equal to 1 or not, it is not here. So, it will call fact_rec(3) and same thing will be repeated.
When x == 1, print(f"I'm here!!!! X is: {x}") will be triggered and the function will return 1 to the calling function i.e fact_rec(2) and so on. Hence, first of all condition for x = 1 will be printed followed by x = 2 and so on.

Please refer the image below:

Function Calls

Upvotes: 1

Related Questions