user4326875
user4326875

Reputation:

Homemade factorial function in Python

I know a code that works, but I can't seem to figure out why this code only returns 0. Can anyone help me fix this?

def factorial(x):
    hold = 1
    count = x
    if x == 0:
        return 1
    else:
        while count > 0:
            count -= 1
            hold *= count
            return hold

Upvotes: 0

Views: 91

Answers (1)

Piotr Dabkowski
Piotr Dabkowski

Reputation: 5939

It returns 0 because count will be finally 0 in your last loop. Loop will execute for count = 1 and you will multiply hold by 0 since you subtract 1 from count before multiplying. You have to subtract 1 after multiplication:

def factorial(x):
    hold = 1
    count = x
    if x == 0:
        return 1
    else:
        while count > 0:
            hold *= count
            count -= 1  # moved this statement to the bottom
        return hold

However much better function would be:

def factorial(x):
   hold = 1
   for number in xrange(2, x+1): # or range in python 3
       hold *= number
   return hold

Upvotes: 3

Related Questions