More

    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.
    Disclaimer: While we make every effort to update the information, products, and services on our website and related platforms/websites, inadvertent inaccuracies, typographical errors, or delays in updating the information may occur. The material provided on this site and associated web pages is for reference and general information purposes only. In case of any inconsistencies between the information provided on this site and the respective product/service document, the details mentioned in the product/service document shall prevail. Subscribers and users are advised to seek professional advice before acting on the information contained herein. It is recommended that users make an informed decision regarding any product or service after reviewing the relevant product/service document and applicable terms and conditions. If any inconsistencies are observed, please reach out to us.

    Latest Articles

    Related Stories

    Leave A Reply

    Please enter your comment!
    Please enter your name here

    Join our newsletter and stay updated!