I know that there are more than one way of calculating the factorial of an integer as well as there is a math
module. However I tried to put together a simple function that is returning a wrong result. I would love to know what went wrong here. Such as if I pass 2 as parameter it returns 3, if 3 it returns 8.
>>>def factorial(n):
if n > 0:
result = n * n-1
factorial(n-1)
return result
>>>factorial (2)
3
How can I fix this?
There are a couple of things wrong with your function:
n > 0
is false.n * n-1
calculates (n * n) - 1
, you probably intended n * (n - 1)
factorial
recursively, but then don't do anything with the result. Currently your code acts just like if you had only written return n * n - 1
inside the if.