(it returns none)---> why?
fact = 1
def factorial(n):
if (n-1)!=0:
global fact
fact=fact*n
n=n-1
print(fact)
factorial(n)
else:
return fact
n=int(input())
g=factorial(n)
print(g)
(it returns none)---> why?
fact = 1
def factorial(n):
if (n-1)!=0:
global fact
fact=fact*n
n=n-1
print(fact)
factorial(n)
else:
return fact
n=int(input())
g=factorial(n)
print(g)
Because you need to return factorial(n)
in factorial function, otherwise it just gets called and does not return any result in the calling function. Also, you don't need the global variable, simply pass it along with n
in the factorial
function itself when doing recursive call.
Also, there's a cleanest solution without any unnecessary variables:
def factorial(n):
if n < 2:
return 1
else:
return n * factorial(n-1)
And if you dont wanna reinvent the wheel just use math
module:
import math
math.factorial(1234)