Hii ,I was making a factorial program in python using recursion/ but I have one doubt : if I run the program I get the error as : " result=xfact(x-1) TypeError: unsupported operand type(s) for : 'int' and 'NoneType'"
But If I run it with the commented statements it works fine .So my question is in the else why my return statent doesn't work ?

``````def fact(x):
if x==1 or x==0:
y=1
else:
#result=x*fact(x-1)
#return result
y=x*fact(x-1)
return y

t=int(input())
for i in range(t):
n=int(input())
y=fact(n)
print(y)``````

## All 4 Replies

When I try both sets of code with Python 3.4 in VS 2015 they seem to work without errors. Of course that's assuming that when you tried using the result variable you also changed all the instances of the y variable to result.

commented: There was some change from Python 2 that may be why they asked. But I omitted that. OP needs to tell all. +11

Here is the code to find the factorial of a python using recursion.This code works fine :

``````def recur_factorial(n):
"""Function to return the factorial
of a number using recursion"""
if n == 1:
return n
else:
return n*recur_factorial(n-1)

num=int(input("Enter the number: "))

print("factorial of ",num," (recursive): ",end="")
print(recur_factorial(num))``````

There are other ways to find factorial too such as iteration, or using a function, or for best performance use dynnamic programming.Here is a detailed article about all these methods: Factorial in Python

A more concise (and still clear) version of that would be

``````def fac(n):
return 1 if n <= 1 else n * fac(n-1)``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.