Python Program to Find Factorial of Number Using Recursion

By | October 3, 2021
Python Program to Find Factorial of Number Using Recursion

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 topics to create this program.

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

Factorial: A factorial of a number is the product of that number and all the integer numbers below it till 1.

Vamware

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

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 Reply

Your email address will not be published. Required fields are marked *