5/15. Change the if order?


#1

Why this doesn't work?


#2

Return should be outside the loop.


#3

Your code is correct. Placing the return outside the elif function will return the answer.

But there is an easier way. Try using a while loop:

For example:

import math

def factorial(x):
    # make sure the input is a positive number:
    x = abs (int (x))
    # create a variable with status x
    ans = x
    # subtract 1 from x!
    x = x - 1
    # create a loop that subtracts one from x after each iteration:
    while x > 0:
        # make the calculation visible to check it.
        print ans, '*', x, ans * x
        ans = ans * x
        x -= 1
    # return the answer after the loop
    return ans

print factorial(10)

#4

def factorial(x):
c=1
for i in range(1, x+1):
c=c*i
return c