0

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
5
  • 1
    you need to set hold to 1. Commented Dec 5, 2014 at 1:31
  • 1
    What do you mean by "doesn't work" Commented Dec 5, 2014 at 1:32
  • The function always returns "0" Commented Dec 5, 2014 at 1:35
  • I edited the post to make it more clear, also adding in @DanielA.White's suggestion. I still get the same problem. Commented Dec 5, 2014 at 1:37
  • 2
    You decrement before multiplying. Switch the order. Commented Dec 5, 2014 at 1:41

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.