Factorial - My code works however, I have a question regarding While statements



My code works however believe my code should also include a else statement which simply outputs 1 in the case of x being 1 or 0. I can't work out how to include it without breaking my code. Adding the else and keeping the indentation on the return causes an unexpected indent whereas indenting the return means it simply executes after only one loop.

I'm sure it must have been covered earlier in the course but I can find any instances which match up with this one, the code below is what I have so far.

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


Place this at the beginning of the function ...

    if x < 1:
        return 1


Thanks for your help.


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

Is this what you mean? Having an "if statement" is probably better for readability, though


Hi @awittyjar,

The second return statement here will never be executed ...

    return result
    return 1

As the first one executes, function execution terminates, and control returns to the statement that called the function.

You can remove the second one since it is unnecessary.


if x == 1 or x == 0:
return 1
elif x < 0:
print "factorial only positive number"

this should sound better as for me