How to compute the factorial of a number in Python

The factorial(!) of a number n is the product of all positive numbers less than or equal to n.

Equation

The factorial of a number is defined as:

factorial(n)=nfactorial(n1)factorial(n)=n * factorial(n-1)

oror

factorial(n)=n(n1)(n2)...1factorial(n)=n * (n-1) * (n-2) ... * 1

Note: The factorial of 0 is 1.

Example

To calculate the factorial of 4, have a look at the following illustration:

4!=43214 != 4*3*2*1

Approaches to compute the factorial of a number in Python

In Python, there are two approaches to computing the factorial of a number:

  1. Iterative Method
  2. Recursive Method

Iterative Method

The following code explains how to compute the factorial of a number using the iterative approach:

def factorial(n):
fact = 1
for num in range(2, n + 1):
fact *= num
return fact

The iterative approach works by setting a base value to 11. For each loop, the method multiplies to the base value until the for loop finishes and you get the final factorial value.

Recursive approach

The recursive approach is when the function calls itself again and again until some stopping condition. It has two parts:

Base case

This is where the recursion stops

Recursive Case

This is the case where the function calls itself again and again until the base condition is reached.

factorial(4)=4factorial(3)factorial(4)=4*factorial(3)

factorial(3)=3factorial(2)factorial(3)=3*factorial(2)

factorial(2)=2factorial(1)factorial(2)=2*factorial(1)

factorial(1)=1factorial(0)factorial(1)=1*factorial(0)

The following illustration explains how to compute the factorial of a number using recursion in Python:

1 of 10
def factorial(n):
if n == 1: #base case
return n
else:
return n*factorial(n-1) # recursive case
number = 4
if number < 0:
print("Factorial exists for positive numbers only")
elif number == 0:
print("Factorial of 0 : 1")
else:
print("Factorial of",number,":",factorial(number))
Copyright ©2024 Educative, Inc. All rights reserved