In math, the factorial of a number is the product of all the factorials of the number’s digits. For example, the factorial of 5 is 120.
A recursive function is a function that calls itself. The most common use of recursion is in mathematical algorithms. Many mathematical problems can be solved more efficiently using recursion.
def recursion_factorial(n): if n < 0: print("Sorry, factorial does not exist for negative numbers") elif n == 0: return 1 else: return n * recursion_factorial(n-1) num = int(input("Enter a number: ")) if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: print("The factorial of",num,"is",recursion_factorial(num))
Enter a number: 7
The factorial of 7 is 5040
- We define a function, recur_factorial(), which takes a number as its parameter.
- Use the if…elif…else statement to check if the number is negative, zero or positive.
- If the number is negative, we print an appropriate message.
- If the number is zero, we print the factorial of zero is one.
- If the number is positive, we call the recur_factorial() function inside the print statement to get the output.