5/10 Should this work? Why it doesn't?


#1
def factorial(x):
    if x == 0 or x == 1:
        result = 1
        return result
    else:
        result = 0
        fact = list(range(x+1))
        for number in fact:
            if number != 0:
                result = result * number
        return result

I get the following error: "Oops, try again. factorial(2) returned 0 instead of 2."

If I understand my code correctly, this is what it does:

Checks if x is 0 or 1, if it is, sets the result to 1. If it's a number larger than 1, it creates a list with the range of x + 1 (3 would be [0, 1, 2, 3] since range(3+1).). Then, it discards the number 0 for the factorization, and multiplies the other numbers.


#2

Once again, I fixed before I got any answers, next time I'll think harder before posting. Sorry.

def factorial(x):
    if x == 0 or x == 1:
        result = 1
        return result
    else:
        result = 1
        fact = list(range(x+1))
        for number in fact:
            if number != 0:
                result = result * number
        return result

#3

Here's what I came up with. It seems to work.

def factorial(x):
    total = 1
    while x > 0:
        total *= x
        x -= 1
    return total

#4

I have such a solution. It works.

def factorial(x):
i = 1
fact = 1
if x == 0:
return fact
elif x<0:
return "The number must be greater than 0 and must be integer"
else:
while i <= x:
fact = fact * i
i += 1
return fact