Program to Find the Factorial of a Number using Recursion in Python

Program to Find the Factorial of a Number using Recursion in Python. This program source code has if else statement and factorial mathematical concept. This program is widely asked in Python practical lab of beginners, class 11,12 and B Tech computer science students. Download source code.

Program to Find the Factorial of a Number using Recursion in Python

What is factorial?

Factorial is a non-negative integer. It is the product of all positive integers less than or equal to that number you ask for factorial. It is denoted by an exclamation sign (!).
Example:
n! = n* (n-1) * (n-2) *……..1  
4! = 4x3x2x1 = 24    
The factorial value of 4 is 24.

What is recursion ?

Recursion is a method in which a function calls itself.

Source code : Program to Find the Factorial of a Number using Recursion in Python

num = int(input("Enter a number: "))  
def fact(n):  
    return 1 if (n==1 or n==0) else n * fact(n - 1);  
  
 
print("Factorial of",num,"is",fact(num)) 

Download Source code : For Download Click on the below Button

Step wise Source Code Explanation:

We have used the recursion to find the factorial of a given number.

1.The number whose factorial is to be calculated is captured.
num = int(input(“Enter a number: “))
2.We have defined the fact(num) function, which returns one if the entered value is 1 or 0 otherwise until we get the factorial of a given number.
num = int(input(“Enter a number: “))
def fact(n):
return 1 if (n==1 or n==0) else n * fact(n – 1);
3.Print the fact(num)
print(“Factorial of”,num,”is”,fact(num))

Output :

Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> 
 RESTART: C:/Users/ARCHIT/AppData/Local/Programs/Python/Python37-32/test1.py 
Enter a number: 6
Factorial of 6 is 720
>>> 
 RESTART: C:/Users/ARCHIT/AppData/Local/Programs/Python/Python37-32/test1.py 
Enter a number: 7
Factorial of 7 is 5040
>>>  

Output Explanation :

Number is captured
Enter a number: 6
The factorial is calculated and displayed
The factorial of 6 is 720
Similarly, 7 factorial is displaying.

Conclusion :

The program is running fine.

Thank you for learning the following Program to Find the Factorial of a Number in Python. This program source code has if else statement and factorial mathematical concept. This program is widely asked in Python practical lab of beginners, class 11,12 and B Tech computer science students. For more programming knowledge click on the below links where practical programs of class 11,12 and beginner is provided.

Python Programs Archives – CS Study

Computer Science with Python Class 11 Sumita Arora Solutions – CS Study

Sumita Arora Python Class 12 PDF : CS Book – CS Study

Leave a Comment

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