Python Program to Find Factorial of a Number
You can find the factorial of a number in Python using a loop like
factorial = 1; for i in range(1, n+1): factorial *= i or using recursion with def factorial(n): return 1 if n == 0 else n * factorial(n-1).Examples
Input0
Output1
Input5
Output120
Input1
Output1
How to Think About It
To find the factorial of a number, think of multiplying all whole numbers from 1 up to that number. For example, factorial of 5 means 1 × 2 × 3 × 4 × 5. You can do this by starting with 1 and multiplying by each number until you reach the input number.
Algorithm
1
Get the input number n2
Start with a result variable set to 13
Multiply the result by each number from 1 to n4
After the loop ends, return the resultCode
python
def factorial(n): result = 1 for i in range(1, n + 1): result *= i return result number = 5 print(f"Factorial of {number} is", factorial(number))
Output
Factorial of 5 is 120
Dry Run
Let's trace factorial(5) through the code
1
Initialize result
result = 1
2
Multiply by 1
result = 1 * 1 = 1
3
Multiply by 2
result = 1 * 2 = 2
4
Multiply by 3
result = 2 * 3 = 6
5
Multiply by 4
result = 6 * 4 = 24
6
Multiply by 5
result = 24 * 5 = 120
| Iteration | Value of result |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 6 |
| 4 | 24 |
| 5 | 120 |
Why This Works
Step 1: Start with 1
We use result = 1 because multiplying by 1 does not change the value and it is the identity for multiplication.
Step 2: Multiply step by step
We multiply result by each number from 1 to n to build the factorial product.
Step 3: Return final result
After the loop finishes, result holds the factorial value, which we return.
Alternative Approaches
Recursion
python
def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) number = 5 print(f"Factorial of {number} is", factorial(number))
Uses function calling itself; elegant but can hit limits for very large n.
Using math module
python
import math number = 5 print(f"Factorial of {number} is", math.factorial(number))
Simplest and fastest way using Python's built-in library.
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs from 1 to n, so it takes O(n) time to compute the factorial.
Space Complexity
Only a few variables are used, so space is O(1), constant.
Which Approach is Fastest?
Using Python's built-in math.factorial() is fastest and most optimized, while recursion is elegant but slower and limited by recursion depth.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Loop | O(n) | O(1) | Simple and clear for beginners |
| Recursion | O(n) | O(n) | Elegant but limited by recursion depth |
| math.factorial() | O(n) | O(1) | Fastest and easiest for production |
Use Python's built-in
math.factorial() for the simplest and most efficient solution.Forgetting that factorial of 0 is 1, not 0.