Factorial - little stuck


Thought I could use a "while" statement for this exercise so please be honest if I'm wayyy off. But I get the following error below and included the code I'm using. Any thoughts?

Oops, try again.
factorial(1) returned 0 instead of 1

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


Did you mean to write,

total = 1



by making total = 1 it causes an infinite loop on my screen.


That's not the cause, though. Examine your while loop. When does x change? Also, where in the definition of a factorial is there any addition?

Recall that factorial(0) and factorial(1) are both 1

n! = n * (n-1) * (n-2) * ... * 1   # n > 0

product = 1   # a good place to start

Now set up a loop that winds down to 2...

while n > 1:
    product *= n
    n -= 1
return product

For this exercise we can assume that the lesson checker will only test with numbers from 0 to some positive integer. However in a more robust function we would test the inputs to be sure they are,

1. 0 or greater
2. integer
3. not very large (factorials grow very rapidly)

Something to work on once you master the basic function.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.