Factorial ! I am stuck


error message:
Oops, try again. factorial(1) returned None, did you remember to return the result?

My question:
I am stuck at my current code because I think it would be okay when input is positive integer. However, it couldn't run at all.

The other question is that sometimes I will feel confuse about the where should I return the value in the program. Inside the for loop or outside of it ? I hope someone can explain the reason that why should I put return code in this position .


def factorial(x):
    num = 1
    for s in range(x-1):
        num = num*(s+1)
        return num

print factorial(4)


the return should be outside the loop, why? Because a function ends the moment a return keyword is reached, so by placing return keyword in the loop, the function ends in the first run/iteration of the loop

to succesfully calculate the factorial, the whole loop need to run succesful.


thanks ! @stetim94 I will use your advice to rewrite the code!


one more thing, here:

for s in range(x-1):

range does not include the stop value (in this case x), so no need to subtract one


THANKS!!! I got it !