Question for 5/15 factorial


#1

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! :smile:


#2

I think it is going to be 4 * 3 and then the function will run itself till it reaches 1 and stops.
I wrote a simpler code, that is:
def factorial(x):
calc = 1
if x == 1 or x == 0:
return calc
else:
for i in range(1, (x + 1)):
calc *= i
return calc


#3

@enddndr That code's pretty neat! Thanks a lot! :smile:


#4

Hello migs08,

the factorial function uses recursion.
So that you will have 4 * the factorial of 3.

Here is a good Picture that describes the functionality of the factorial function:


#5

@krissi94 Hey thanks a lot for that diagram! That sorted it out! Great find!