0

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))
2
  • 1
    just a side note, what if the user inputs zero? Commented Jun 19, 2021 at 15:49
  • zero is not negative Commented Jun 19, 2021 at 15:49

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.