In this tutorial, you’ll learn how to calculate factorials in Python. Factorials can be incredibly helpful when determining combinations of values. In this tutorial, you’ll learn three different ways to calculate factorials in Python. We’ll start off with using the math
library, build a function using recursion to calculate factorials, then use a for loop.
By the end of this tutorial, you’ll have learned:
- What factorials are and why they’re important
- How to use for loops to calculate factorials
- How to build a recursive function to calculate factorials
Table of Contents
What are Factorials and Why Do They Matter?
The factorial of a number is calculated as the product of all the integers from 1 to that number. Factorials are displayed as the number followed by an exclamation mark. For example, the factorial for the number 7
is 7!
.
Let’s see what this means and how we can calculate the factorial for 7!
:
7! = 1 * 2 * 3 * 4 * 5 * 6 * 7 = 5040
There are some important things to note about factorials:
- The factorial of 0,
0!
, is 1 - The factorial of any negative number is undefined
At this point, you may be wondering what the point of factorials is. Factorials allow us to calculate how many combinations or orderings of different items are. Given a list of, say, three items such as [1,2,3]
, there are 3! different combinations of the data.
Similarly, factorials allow us to find permutations of subsets. Say we wanted to find the number of combinations that a group of 10 people could come into first, second, and third place. With this, we could use the formula 10! / (10-3)!
, which reduces down to 10! / 7!
, which further reduces to 10 * 9 * 8 = 720
combinations.
How to Calculate Factorials with Python’s Math Module
One of the simplest ways to calculate factorials in Python is to use the math
library, which comes with a function called factorial()
. The function returns a single integer and handles the special case of 0!
. Similarly, the function error handles when attempting to find the factorial of a negative number.
Let’s try finding the factorial of 7 using the math
library:
# Finding Factorials with math.factorial()
import math
print(math.factorial(7))
# Returns: 5040
Similarly, let’s try getting the factorial of a negative number:
# Finding the factorial of a negative number
import math
print(math.factorial(-7))
# Raises: ValueError: factorial() not defined for negative values
In the next section, you’ll learn how to create a function to calculate factorials in Python.
How To Create a Function To Calculate Factorials with Recursion
In this section, you’ll learn how to create a function that calculates factorials with recursion. Building this function recursively allows you to define a function that is simple and elegant. Let’s see how this function looks and then explore how it works:
# Building a recursive function to calculate factorials
def factorial(number):
if number < 2:
return 1
else:
return number * factorial(number - 1)
print(factorial(7))
# Returns: 5040
If you’re not familiar with recursion (or just want a refresher on how it works), let’s break down the steps that the function takes:
- The function takes a single argument,
number
- If the number is less than 2 (meaning: 1), it returns 1. This is the closing case which doesn’t call itself.
- If the number is 2 or higher, then the function returns that number multiplied by the value returned when the function is called again for that number minus 1.
If this is a bit mind-bending, don’t worry – you’re not alone! Let’s break this down a little further. Let’s imagine we call the function with the number of 3:
- The function returns
3 * factorial(2)
- This, in turn, returns
2 * factorial(1)
- This, then returns
1
We can then move back up our chain where we now get: 1 * 2 * 3
, which equals 6! In the next section, you’ll learn how to use a for loop to calculate factorials in Python.
Using a For Loop to Calculate Factorials in Python
In this final section, we’ll use a for loop to calculate a factorial of a number in Python. This can be a more readable and approachable approach to calculating factorials than recursion. It also doesn’t require any additional libraries, which can be helpful in programming interviews!
We’ll use the augmented assignment operator to make our code a little slimmer. Let’s see what this looks like:
# Using For Loops to Calculate Factorials
def factorial(number):
num = 1
for i in range(1, number+1):
num *= i
return num
print(factorial(7))
# Returns: 5040
In this section, you learned how to use for loops to calculate factorials in Python.
Conclusion
In this tutorial, you learned about factorials in Python. You learned what factorials are and why they’re important. You then learned three different ways of calculating factorials. First, you learned how to calculate factorials with the Python math
library. Then, you learned how to calculate factorials using a recursive function. Finally, you learned how to use for loops to calculate factorials.
Additional Resources
To learn more about related topics, check out the tutorials below: