Hey guys, this is **Minh Vu** again with 2 years experience in Python.

This time, I will show you how to **find the factorial of a number** in Python.

Actually, the algorithms is similar to another tutorial about Fibonacci sequence I wrote before, which uses recursion and for loop to find the Fibonacci sequence.

## Table of Contents

## What is Factorial of a Number?

Factorial of a number is the product of all integers **from 1 to that number**.

For example, the factorial of 5 is `1 x 2 x 3 x 4 x 5 = 120`

.

## How to Find Factorial of a Number in Python?

To find the factorial of a number in Python, you can:

- Use the built-in function
`math.factorial()`

- Use recursion
- Use a for loop

The first method is straightforward as Python already has a built-in function for this.

The second and third methods are for those who want to understand what it does behind the scene.

### Using math.factorial()

The easiest way to calculate the factorial of a number is to use the `math.factorial()`

function.

Create a file called `main.py`

and add the following code:

`import math while True: if n <= 0: print("Stop") break n = int(input("Enter a number: ")) print(math.factorial(n))`

The above code will ask to enter a number until it reaches a negative integer.

Let's test it out by running the following command:

`python main.py`

You will get:

`Enter a number: 5 120 Enter a number: 10 3628800 Enter a number: -1 Stop`

### Using Recursion

**Recursion** is an advanced technique that can be used to find the factorial of a number.

Remember that for recursion to work, we should have a **base case** and a **recursive case**.

From the definition of the factorial, we can see that:

- Base case:
`factorial(0) = 1`

- Recursive case:
`factorial(n) = n * factorial(n - 1)`

Let's implement this in Python:

`def factorial(n): if n == 0: return 1 return n * factorial(n - 1) while True: n = int(input("Enter a number: ")) if n < 0: print("Stop") break print(factorial(n))`

Running the above code, we get the same result:

`Enter a number: 20 2432902008176640000 Enter a number: 6 720 Enter a number: -1 Stop`

This method is more complicated and less efficient as we should avoid using recursion as much as possible. So let's move to the next method.

### Using For Loop

The last method is to use a **for loop** to calculate the factorial of a number in Python.

`def factorial(n): result = 1 for i in range(1, n + 1): result *= i return result while True: n = int(input("Enter a number: ")) if n < 0: print("Stop") break print(factorial(n))`

In this case, we converted the recursion into a for loop.

## Conclusion

I have shown you 3 ways to find the factorial of a number in Python.

- Using
`math.factorial()`

- Using recursion
- Using a for loop

In practice, I recommend using the `math.factorial()`

function as it's the easiest and most efficient way.