Hi guys. I have this code for this factorial activity, which runs perfectly fine. This was actually done by my friend way back. However I just need to clarify something about this code. Take a look at this:
def factorial(x): if type(x) != int or x < 0: return "Error - x must be a positive integer" elif x == 0 or x == 1: return 1 else: return x * factorial(x-1) print factorial(4)
My question is for the else statement. Say for example I use 4 for x. From what I understand, that else statement is converted to:
return 4 * factorial(4-1)
Is that right? If it is, then the next sequence is:
return 4 * factorial(3)
My question is, how does this operation work? Is it going to be 4 * 3 and then the function runs itself again until it reaches the elif condition "1" and then it stops? Or is 4 being multiplied to the factorial of 3 (that is 3 x 2 x 1)? I'm not sure for the last part because I think you have to call the module for math in order to call factorial right? If both of my ideas were wrong, then what's the proper explanation of how this code worked?
I hope you guys could help me out. Thanks a lot in advance!