Summary: In this programming example, we will learn different ways to find the factorial of a number in Python.

The factorial of any non-negative number is the product of all integers from 1 to that number.

Example: Factorial of 4 is 1*2*3*4=24.

Let’s see different methods to find factorial in Python.

Method 1: Iterative Method

In this method, we iterate from 2 to the input number using a for loop and multiply the iterative variable to get the factorial.

#input a number
num = int(input("Enter a number: "))
factorial=1

#iterate from 2 to n (including)
for x in range(2, num+1):
    #multiply iterative variable to the factorial
    factorial = factorial*x

#output the factorial
print("Factorial: ",factorial)

Output:

Enter a number: 5
Factorial: 120

Method 2: Recursive Method

In this method, we write a recursive function that multiply the number until it reduces to 1.

#recursive function
def factorial(n):
    return 1 if n==1 or n==0 else n*factorial(n-1)
    
num = int(input("Enter a number: "))
print("Factorial: ", factorial(num))

Output:

Enter a number: 4
Factorial: 24

Method 3: Using math.factorial()

Python has an inbuilt factorial() method defined in the “math” module that returns the factorial of non negative integral number.

Syntax:

math.factorial(n)

Parameter:

n– A number whose factorial need to be calculated.

Example:

import math
    
num = int(input("Enter a number: "))
print("Factorial: ", math.factorial(num))

Output:

Enter a number: 6
Factorial: 720

Leave a Reply