Progress

Python program to find factorial of a Number using Recursion and For loop

Python program to find factorial of a Number using Recursion and For loop

Problem Statement: Write a Python program to find factorial of a number using recursion and the loop.

Description: Factorial of a number can be calculated by the following formula.

n! = n*(n-1)*(n-2)*(n-3)........(3)*(2)*(1)

Note that that factorial of 1 is 1 and 0 is also 1.

Example:

Input: 5
Output: The Factorial of 5 is 120.
Explanation: 5*4*3*2*1 = 120

Input: 7
Output: The Factorial of 7 is 5040.
Explanation: 7*6*5*4*3*2*1 = 5040

Enough of theory now lets jump right into coding a Python program to find factorial of a number.

Python Program: Find Factorial using For loop

This is the easiest approach to find factorial of a number which is easy to understand for beginners. It is a general solution for beginners to use for loop to find factorial of a number.

factorial.py
Copy
num = int(input("Enter the Number: "))
fact = 1
for i in range(1, num+1):
    fact*=i
print(fact)
Output
Enter the Number: 5
The factorial of 5 is 120

We take the input and convert to integer type in the first line because by default input() returns string.

The for loop has ranged from 1 to num (inclusive) and we multiply each value to the variable fact. This is same as we described in the formula.

Python Program: Find factorial using recursion

This is the most popular way to find factorial of a number. In a programming interview, it is often asked to write a Python program to find factorial of a number using recursion.

Copy
def find_fact(num):
    if(num==1):
        return 1
    return num*find_fact(num-1)

if __name__ == "__main__":
    num = int(input("Enter the Number: "))
    print("The factorial of {0} is {1}".format(num, find_fact(num)))
Output
Enter the Number: 5
The factorial of 5 is 120

Recursion may be a confusing topic for beginners but it is easy to understand.

Here is the image that explains the breakdown of the recursive function.

Find factorial Using Math module

Copy
import math
num = int(input("Enter the Number: "))
fact = math.factorial(num)
print("The factorial of {0} is {1}".format(num, fact))
Output
Enter the Number: 5
The factorial of 5 is 120

The inbuilt math module in Python is very useful when dealing with mathematical operations. It has some very optimized functions to do various calculations behind the scenes.

The math module also has an inbuilt function to find factorial of a number. The fact() function takes an integer number as argument and returns the factorial of the number.

Related Python Examples:

Share the Post ;)

Related Posts