Python Program to Find Factorial of Number Using Recursion

Posted in

Python Program to Find Factorial of Number Using Recursion
vinaykhatri

Vinay Khatri
Last updated on November 21, 2024

    Here in this article, we have provided a python source code, which asks the user to enter a number and in the output display its factorial. Here rather than using a Loop structure we have created this program using the recursive technique.

    Prerequisite Python Program to Find Factorial of Number Using Recursion

    • Python Input, Output
    • Python User-Defined Function
    • Python Recursion
    • Python if…else statement

    What is Factorial?

    A factorial of a number is the product of that number and all the integer numbers below it till 1. for instance, the 4 factorial would be 4*3*2*1 = 24 By default, the 0 and 1 factorial is 1.

    Steps:

    • First, ask the user to enter a number.
    • Create a recursive function which calls itself till the base condition get satisfied.
    • Here recursive logic would be num*function(n-1).

    Python Program to Find Factorial of Number Using Recursion

    Python Code

    def fact(num):
        if num == 1:
            return num
        else:
            #recursion
            return num*fact(num-1)
    
    print("-------------Factorial Calculator-------------------")
    num = int(input("Enter the Number: "))
    if num > 0:
        print(num,"!","is:", fact(num))
    elif num == 0:
        print("The 0! is 1")
    else:
        print("Enter a valid Number")

    Output 1:

    -------------Factorial Calculator-------------------  
    Enter the Number: 12
    12 ! is: 479001600

    Output 2:

    -------------Factorial Calculator-------------------
    Enter the Number: 7
    7 ! is: 5040

    People are also reading:

    Leave a Comment on this Post

    0 Comments