This short article will show you the quickest and easiest way to calculate a factorial in Python using the factorial() function.
This article is written for the Python 3 programming language.
What is a Factorial, and How is it Calculated?
A factorial is a mathematical formula in which a given positive integer is multiplied by all of the positive integers less than itself – the resulting number being the factorial of the original number.
It is denoted with ! (exclamation mark) – so the factorial of 4 is written as
And is calculated out like so:
4 * 3 * 2 * 1 = 24
The Python Factorial Function
You could write a Python function that does the above calculation yourself – but you don’t have to!
Python already has a built-in factorial function ready to do the job for you. It’s in the math library – just import it and use it:
import math factorial = math.factorial(4) print(factorial)
Negative Numbers/Bad Input
Factorials can only be calculated from positive integers. If you pass anything else to the factorial() function, you’ll receive an error.