How To Find Factorial Of A Number In Python

In this tutorial, we will learn how to calculate the factorial of a number using Python. Factorials are commonly used in mathematics, especially in combinatorics and probability theory.

Calculating the factorial of a number involves multiplying all the positive integers from 1 to that number. For example, the factorial of 5 (denoted as 5!) is calculated as 5 * 4 * 3 * 2 * 1 = 120.

Let us learn three different methods to find the factorial of a number in Python: iterative method, recursive method, and using the math module in Python.

Method 1: Iterative Method

In this method, we will use a loop to iterate through the range of numbers from 1 to the given number (inclusive) and multiply them together. Here are the steps:

  1. Initialize a variable to store the factorial result, let’s call it result and set its initial value to 1.
  2. Use a for loop to iterate through the range of numbers from 1 to the given number (inclusive).
  3. In each iteration, multiply the result with the current number in the loop.
  4. After the loop, print the final value of result.

Output:

Factorial of 5 is: 120

Method 2: Recursive Method

In this method, we will create a recursive function to calculate the factorial of a number. Here are the steps:

  1. Create a function, let’s call it find_factorial_recursive.
  2. Inside the function, check if the number is 0 or 1:
    a. If the number is 0 or 1, return 1.
    b. If the number is greater than 1, return the product of the number and the result of calling the function again with number – 1, i.e., number * find_factorial_recursive(number - 1)
  3. Call the function with the number whose factorial needs to be calculated and print the result.

Output:

Factorial of 5 is: 120

Method 3: Using the math module

Python’s built-in math module provides a function factorial() that can be used to calculate the factorial of a number. Here are the steps:

  1. Import the math module.
  2. Call the math.factorial() function with the number whose factorial needs to be calculated.
  3. Print the result.

Output:

Factorial of 5 is: 120

Full Code

Output:

Factorial of 5 (Iterative): 120
Factorial of 5 (Recursive): 120
Factorial of 5 (Math Module): 120

Conclusion

In this tutorial, we have learned three different methods to calculate the factorial of a number in Python: iterative method, recursive method, and using the math module. Each method has its benefits and drawbacks, but the easiest way is to use the math.factorial() function from the math module. Now you can apply these methods to find the factorial of any number in your Python projects.