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.
- What is Factorial of a Number?
- How to Find Factorial of a Number in Python?
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.
To find the factorial of a number in Python, you can:
- Use the built-in function
- 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.
The easiest way to calculate the factorial of a number is to use the
Create a file called
main.py and add the following code:
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:
You will get:
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:
Running the above code, we get the same result:
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.
The last method is to use a for loop to calculate the factorial of a number in Python.
In this case, we converted the recursion into a for loop.
I have shown you 3 ways to find the factorial of a number in Python.
- Using recursion
- Using a for loop
In practice, I recommend using the
math.factorial() function as it's the easiest and most efficient way.