Factorials - Why does this code actually work?


For this part, I had to eventually cheat and look up the answers, below is the code that I found and somehow works, but why?

def factorial(x):
if x == 1 or x == 0:
print (1)
return 1
return x*factorial(x - 1)

It returns:

My questions are:
-Why does it return a 1? The "if" statement is false so it shouldn't execute in the first place, then it should go to the "else" statement.

-How did it get 24? If you follow the logic, it should return 12 as x*factorial(x - 1) -> 4*(4-1) -> 12


you use recursion here:

return x*factorial(x - 1)

so, now the function will call itself again (with value 3 (4 -1)), then again with 2, and then again with 1, till the base case (if x == 1 or x == 0:) is reached

there is a very detailed topic about recursion here:


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.