Home » Programming » Python » Python Factorial

Calculating Factorials in Python – The Easy Way

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?

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

You can find out more about factorials themselves on Wikipedia.

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)


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.

Photo of author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment