Javaexercise.com

How to Find Factorial of Any Number in Python

This article is about to find a factorial of any number in Python. In mathematics, a factorial is a positive number and represented as n!. A factorial is a product of all positive integers less than or equal to n. For example, if we calculate the factorial of 3, then the product of all integers less than 6 will be 3*2*1 = 6. It means the factorial of 3 is 6. Now, let's implements it using the Python program. 

Algorithm To Find Factorial in Python

Step 1: Take a number

Step 2: Check whether the number is greater than 1

Step 3: Iterate a loop for all the values less than the number

Step 4: Calculate factorial 

Step 5: Repeat step 3 and 4 until the loop exits

Step 6: Display factorial

 

Note: This algorithm is to calculate the factorial without using math.factorial() method. You can see its implementation in example2 below.

 

Python Program to Find Factorial of Given Number using math.factorial() Method

Python provides a math module that contains the factorial() method. We can use this method to calculate factorial for any number as we did in the below code example. 

import math
# Take a number
num = 5
print(num)
fact = 1
# Find factorial
fact = math.factorial(num)
# Display result
print("Factorial is: ",fact)

Output:

5

Factorial is:  120

 

Python Program to Find Factorial of Given Number

In this example, we are using for loop to calculate the factorial of a number. We can use this code if don't want to use math.factorial() method. See the code and output.

# Take a number
num = 5
print(num)
fact = 1
# Find factorial
if num >= 1:
    for i in range (1, num+1):
        fact = fact * i
# Display result
print("Factorial is: ",fact)

Output:

5

Factorial is:  120

 

Python Program to Find Factorial of Given Number using Recursion.

Recursion is a technique in which a function calls itself until the base condition. Here, we used the recursion approach to find a factorial of a number in Python. See the code and output.

# Take a number
num = 5
print(num)
fact = 1
# Find factorial
def factorial(num):
    if num < 2:
        return 1
    else:
        return num * factorial(num-1)
# Display result
print("Factorial is: ",factorial(num))

Output:

5

Factorial is:  120