Python Program to Find Factorial of a Number Using Recursion

Factorials

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.

Recursion

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.

Program Code

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))

Input Given:

Enter a number: 7

Output Expected:

The factorial of 7 is 5040

Code Explanation

  1. We define a function, recur_factorial(), which takes a number as its parameter.
  2. Use the if…elif…else statement to check if the number is negative, zero or positive.
  3. If the number is negative, we print an appropriate message.
  4. If the number is zero, we print the factorial of zero is one.
  5. If the number is positive, we call the recur_factorial() function inside the print statement to get the output.

Leave a Comment

Share to...