Facotrial — Why wouldn't this work?


#1




My code returns 12 for factorial(4)


I want it to return 24


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


#2

ans just get assigned a value. No matter what is already stored in ans, it gets overwritten, look:

def factorial(x):
    if x==0:
        return 1
    elif x == 1:
        return 1
    else:
        count = x
        while count > 0:
            ans = x*(x-1)
            print(ans)
            count -= 1
            if count == 0:
                return ans
print factorial(4)

its your code with some print statements and a function call

and x doesn't change in the loop.


#3

Thanks, appreciate it


#4

did you manage to solve it with this hints?


#7

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