5. factorial


#1

Hello,
Could someone please explain to me why my code isn't working properly?
I know that my solution is not elegant. I get this error message:
Oops, try again. factorial(4) returned 12 instead of 24

The goal is to create a function which calculates the factorial of x.
But when I print factorial(5) it prints 20

Thank you in advance.


def factorial(x):
    original = x
    while x is not 0:
        if x == original:
            factor = x
            x -= 1
        else:
            factor *= x
            x -= x
    else: 
        return factor
        
print factorial(5)


#2

this line:

x -= x

x -= x will always be zero. which means, in the first run of your loop, if will be true, x will be reduced by one (as it should) in the next run, else will run, and x will be reduced to zero, instead of being reduced in steps of 1 (to cover all values)


#3

Thanks!
I tried many things but overlooked such a simple mistake :confused: