Calculating Factorial in Python

This is a detailed tutorial on calculating factorial in python. Learn to find factorials in python using recursion and using the math library factorial method.

Factorial

A Factorial is basically a positive integer that is the result of the multiplication of all of the other positive integers from 1 to the number whose factorial is to be calculated. Let x be a positive integer number and the factorial of x will be defined as below.

The exclamation symbol used after the integer number is used to denote the factorial of the number. For example, if you want to calculate the factorial of 5, then it will be 120 as a result of the following mathematical multiplication of the positive integers from 5 to 1.

5! = 5 * 4 * 3 * 2 * 1 = 120

Find more about factorial here and let’s find out how you calculate factorial in python.

Calculating Factorial in Python

There are several different methods that you can use to calculate the factorial of a number in python. In this article, we’ll discuss the three different methods using which you can easily calculate factorials in your python program.

Using For Loop

You can easily calculate factorial using python for loops. This is a naive method as practically it is hardly used. But this method is good for beginners to get a better understanding of the practical usage of the for loop to calculate the factorial.

Example. In the following example, we’re calculating the factorial of the integer number 5 using this method.

#The number of which factorial is to be calculated
number = 5
#Setting intial value of factorial variable to 1
factorial = 1
#Multiplicating numbers from 1 to the number
for x in range(1,number + 1):
    factorial *= x

#Printing the calculated factorial 
print(factorial)

We’re storing the number for which we want to calculate the factorial in the variable named number. Then we’re initializing the factorial variable to be 1. Then we’re doing iteration from 1 to 5 using the range function and for a loop. The range (x, y + 1) does iteration from x to y, therefore, we’ve used the function range(1, number + 1) to do iteration from 1 to the number for which we want to calculate the factorial.

And inside the for loop block, we’re just multiplying the number by the previous factorial, and this way using the assignment operator *=, the result is multiplied by the previous multiplication result and is stored in the variable factorial. Hence, we’re printing the final value of the variable factorial.

Python Factorial Using For Loop Example

Using Recursion

Another way to calculate factorial is to use Python functions and do recursion. Recursion is a method in which we call a function inside the body of the function itself. This is a highly compute-intensive way and sometimes for the calculation of the factorials of larger numbers, this may take a noticeable time for the program to complete its execution.

Example. The following code illustrates a recursive function that calculates factorial.

#Recursive Function To Calculate Factorial
def factorial(number):
    if number == 1:
        return number
    else:
        return number * factorial(number - 1)

#Calling Factorial Function
result = factorial(5)
print(result)

In the above code, we’ve defined a function named factorial that accepts a parameter named number. It is basically the number for which we want to calculate the factorial. Inside the function, we’ve used an If-else statement, if the number is equal to 1, we’re simply returning 1 as the factorial of 1 is 1 but if the value is any other integer, then we’re returning the number multiplied by the factorial of its previous number.

This way the recursion is happening and the result will not be returned until the calculation of the previous number for the same function is not completed. When the calculating of the reversed most function is completed, it starts on multiplying the result wherever they had to be multiplied and this way, the final value for the factorial of the number is calculated.

Python Calculate Factorial Using Recursion

Using math.factorial() Method

Well, if you do not want to write much code to calculate factorial, you can do it using Python’s in-built library of mathematical calculations. It’s called math and it provides a lot of useful methods to reduce your job of writing your own code for complex mathematical calculations.

This library offers a method factorial(number) that can be used to calculate factorial quickly. This method takes the number as the argument for which you want to calculate the factorial.

Example. You can notice in the following example that using this method, we’re able to calculate the factorial, actually in just one line of code.

#Importing math module
import math
#Using math.factorial() method
factorial = math.factorial(5)
print(factorial)

You must first import the math module and then you can make use of this method anywhere in your python program.

Python Factorial Using Math.factorial() Example

In any of the above methods, if you taking the number for which you want to calculate the factorial from Python Input, then you must check if the number is a valid positive integer or not. Because the factorial of negative numbers does not exist. You can use Try Except and if-else statements in python for the purpose to check whether the number is valid for the calculation or not.

The function math.factorial() raises an exception if the number is negative or not valid. Therefore using Try except will be better to use for factorial calculation in this method.

I hope you found this guide useful. If so, do share it with others who are willing to learn Python. If you have any questions related to this article, feel free to ask us in the comments section.

Leave a Reply

Your email address will not be published. Required fields are marked *