Factorial ! I am stuck


#1



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 .

Thanks!


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

print factorial(4)


#2

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.


#3

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


#4

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


#5

THANKS!!! I got it !


#6