Hit enter after type your search item

How to get factorial in Python?

Before version 2.6 of Python, you had to calculate the factorial by writing your own function/code. From version 2.6 and above, the factorial can be calculated by using the built-in function math.factorial(x) which is part of the math module.

In this tutorial, I will show you examples of getting the factorial by both ways: Using the math module’s factorial function and writing custom functions for getting the factorial.

How to use factorial function?

The built-in factorial function can be used as follows:

math.factorial(x)

The function returns the factorial of argument x.

If a negative value or non-integral value is given, the ValueError is generated.

An example of factorial function

In this example, I used four different integer values to get the factorial by using the math.factorial function. See the code and output below:


The result:

The factorial of 10 =  3628800

The factorial of 20 =  2432902008176640000

The factorial of 25 =  15511210043330985984000000

The factorial of 100 =  265252859812191058636308480000000

What is factorial? In Mathematics, the factorial is the product of the whole numbers from the given number to 1. For example, the factorial of 5 is:

5 * 4 * 3 * 2 * 1 = 120

What if a non-integer is passed to factorial function?

The example shows using a float number in the factorial function. See what it results in?


The result:

“ValueError: factorial() only accepts integral values”

Did you know? The factorial for 0 is equal to 1.

Writing a custom function for getting factorial

If you still prefer writing your own function to get the factorial then this section is for you. Here, I will give three different functions for getting the factorial of a number. The aim of each function is to multiply the numbers downwards until it reaches 1 from the given number:

Function Number 1:


The output:

Python factorial

Using for loop and range example

In the following custom function for getting the factorial, a for loop and range is used. The factorial of 0 and other numbers is as shown in the output below:


The output:

Factorial of 0 =  1

Factorial of 1 =  1

Factorial of 17 =  355687428096000

Factorial of 19 =  121645100408832000

Factorial of 21 =  51090942171709440000

Factorial of 23 =  25852016738884976640000

Factorial of 25 =  15511210043330985984000000

Factorial of 27 =  10888869450418352160768000000

Using while loop to calculate factorial

This function uses a while loop for calculating the factorial of the given number:


The result:

0 =  1

1 =  1

11 =  39916800

15 =  1307674368000

17 =  355687428096000

19 =  121645100408832000

21 =  51090942171709440000

23 =  25852016738884976640000

 

This div height required for enabling the sticky sidebar