Factorial in Python: Here, we will figure out how to locate the factorial of a given number utilizing the recursion in Python?
Given a whole number and we need to locate the factorial of the number utilizing recursion in Python.
Example:
Input:
num = 3
Output:
Factorial of 3 is: 6
#3! = 3x2x1 = 6
Note: Factorial of 0 and 1 will be 1
Program
# 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