Home »
Python »
Python programs
Python | Find the factorial of a number using recursion
Factorial in Python: Here, we are going to learn how to find the factorial of a give number using the recursion in Python?
Submitted by IncludeHelp, on August 09, 2019
Given an integer number and we have to find the factorial of the number using recursion in Python.
Example:
Input:
num = 3
Output:
Factorial of 3 is: 6
#3! = 3x2x1 = 6
Note: Factorial of 0 and 1 is 1
Python code to find factorial using recursion
# Python code to find factorial using recursion
# recursion function definition
# it accepts a number and returns its factorial
def factorial(num):
# if number is negative - print error
if num < 0:
print("Invalid number...")
# if number is 0 or 1 - the factorial is 1
elif num == 0 or num == 1:
return 1
else:
# calling function itself i.e. recursive
return num * factorial(num - 1)
# main code
if __name__ == '__main__':
#input the number
x = int(input("Enter an integer number: "))
print("Factorial of ", x, " is = ", factorial(x))
x = int(input("Enter another integer number: "))
print("Factorial of ", x, " is = ", factorial(x))
x = int(input("Enter another integer number: "))
print("Factorial of ", x, " is = ", factorial(x))
Output
Enter an integer number: 5
Factorial of 5 is = 120
Enter another integer number: 0
Factorial of 0 is = 1
Enter another integer number: -3
Invalid number...
Factorial of -3 is = None
Python Basic Programs »
ADVERTISEMENT
ADVERTISEMENT