This article covers several ways to find the factorial of a number in Python with examples, ranging from traditional iterative techniques to more concise recursive implementations and the utilization of built-in library functions.
By understanding these different approaches, you can select the most efficient and suitable method for your specific needs, enhancing your problem-solving capabilities in Python.
Table of contents
What is Factorial
The factorial of a number is the product of all the positive integers from 1 to that number. The factorial of a non-negative integer ‘n’, denoted as n!.
To calculate a factorial, multiply the number by each previous integer until you reach 1.
- The factorial formula is: n! = n * (n-1) * (n-2) * (n-3)…* 1
- For example, the factorial of 3 is 3! = 3 * 2 * 1 = 6
- The factorial of 0 is 1 (0!=1).
You can also calculate a factorial by multiplying the number by the factorial of the previous number. For example, to calculate 6!, you can multiply 5! (120) by 6 to get 720.
1. Find Factorial of a Number in Python using for Loop
Using a Loop (Iterative Method)
The for loop is an easy method to find the factorial of a number in Python. It involves multiplying numbers from 1 to the given number using a for loop.
Code Example
Output:
Factorial of 5 is : 120Code language: Python (python)
Explanation
- Factorial is only defined for non-negative integers, so negative numbers return an error message.
- Initialize
factorial = 1. - Loop from 1 to n.
- Multiply factorial by the current value of the loop counter i.
2. Using Recursion
Recursion involves calling the same function within itself to compute the factorial in Python. The function calls itself with a smaller value (n - 1), continuing until it reaches the base case. The recursive calls multiply n by the factorial of n-1.
How Recursion Works (Tracing factorial_recursive(3)):
Let’s manually trace the recursive calls:
factorial_recursive(3) = 3 × factorial_recursive(2)factorial_recursive(2) = 2 × factorial_recursive(1)factorial_recursive(1) = 1 (Base case)
Now, returning values:
factorial_recursive(2) = 2 × 1 = 2factorial_recursive(3) = 3 × 2 = 6
Final output: 6
Code Example
Explanation
- In the above example,
factorial_recursive()is a recursive function that calls itself. - Error case: Factorial is only defined for non-negative integers, so negative numbers return an error message.
- Base case: The factorial of
0and1is always1, so the function directly returns1in these cases. - Recursive case: Multiply
nbyfactorial(n-1). Here, the function will recursively call itself by decreasing the value of the n, continuing until it reaches the base case.
3. Using Python’s Built-in math.factorial Function
math.factorial() is a built-in function in Python’s math module that returns the factorial of a given non-negative integer.
Code Example
Explanation
- We are using
math.factorial(n)in Python to find the factorial of the given number. It is efficient and well-optimized. nmust be a non-negative integer (n ≥ 0).- Returns an integer value.
- Raises a
ValueErrorfor negative numbers or non-integer inputs.
4. Using reduce from functools
In this approach, we use reduce() with lambda function to calculate the factorial of a number.
The reduce() function in Python (from functools module) applies a given function cumulatively to elements of an iterable, reducing it to a single value.
Syntax:
from functools import reduce
reduce(function, iterable)Code language: Python (python)
A lambda function in Python is an anonymous, single-expression function defined using the lambda keyword, often used for short, inline operations.
Syntax: lambda arguments: expression
For Example, result = reduce(lambda x, y: x * y, [1, 2, 3, 4])
In this example, we are applying the lambda function (x * y) to all values in the list [1, 2, 3, 4]. So, the output is 24 (1*2*3*4).
Code Example
Explanation
- Lambda Function:
- The lambda function here (lambda x, y: x * y) takes two inputs:
- x: Accumulator (stores the cumulative product).
- y: Current number from the range.
- It multiplies these two values and returns the product.
- The lambda function here (lambda x, y: x * y) takes two inputs:
range(1, n + 1)generates numbers from 1 to n.reduce()function applies a lambda function(x * y)to numbers in the range 1 to n.- The result of each multiplication is carried forward.
- For Example, n = 5
- Initial accumulator value: 1.
- Multiply: 1 * 1 = 1 (first number in the range).
- Multiply: 1 * 2 = 2.
- Multiply: 2 * 3 = 6.
- Multiply: 6 * 4 = 24.
- Multiply: 24 * 5 = 120.
- The result is 120.
Summary
These are different ways to find the factorial of a number in Python, showcasing diverse methods to achieve this. It begins by demonstrating the fundamental iterative approach, employing a for loop to accumulate the product of integers. Subsequently, it explores the elegant and concise recursive method, where the factorial of ‘n’ is defined in terms of the factorial of ‘n-1’.
Furthermore, the article highlights the use of the math.factorial() function from Python’s standard library, providing a readily available and optimized solution.
Article also discuss the use of lambda functions, reduce functions, or other advanced techniques.
By presenting these varied implementations, the article provides a comprehensive overview of factorial calculation in Python, enabling readers to choose the most appropriate technique based on factors like performance, readability, and the specific context of their application.
- Use
math.factorial()for the simplest and most optimized approach. - Use loops if built-in functions aren’t allowed.
- Use recursion for learning purposes, but avoid it for large numbers.

Leave a Reply