Factorial Program using Recursion
Factorial Program using Recursion
In the following Python program, we write a factorial()
recursive function. This function returns 1 if the argument is 0 or 1, or calls itself if the number is greater than 1. If the given number is less than 0, then the function shall print a message to the output, and return None.
Python Program
#recursion function
def factorial(n):
if n < 0:
print('Invalid input to find factorial.')
elif n==1 or n==0 :
return 1
else :
return n * factorial(n - 1);
#read input from user
n = int(input('Enter a number: '))
#call recursion function
result = factorial(n)
#print result
print(result)
Output 1
Enter a number: 5
120
Output 2
Enter a number: 0
1
Output 3
Enter a number: -8
Invalid input to find factorial.
None