Factorial Program in Python
In this lesson: Find factorial in Python using loop, recursion and math.factorial — code with output and explanation. In Hindi & English.
What is a factorial
The factorial of a number n (written n!) is the product of all whole numbers from 1 up to n. For example, 5! = 1 × 2 × 3 × 4 × 5 = 120. We can compute it in Python with a loop, with recursion, or with a built-in function.
0! = 1. Your code should return 1 when n is 0.Factorial with a loop
n = 5
f = 1
for i in range(1, n + 1):
f = f * i
print("Factorial:", f)
We start f at 1 and multiply it by each number from 1 to n. range(1, n+1) goes 1, 2, 3, 4, 5 — note the +1 so n is included.
Dry run of the loop
| i (range 1 to 5) | f * i | f now |
|---|---|---|
| 1 | 1 * 1 | 1 |
| 2 | 1 * 2 | 2 |
| 3 | 2 * 3 | 6 |
| 4 | 6 * 4 | 24 |
| 5 | 24 * 5 | 120 |
| Loop ends. Factorial = 120 | ||
f starts at 1 and gets multiplied by each number in turn (1×1×2×3×4×5). range(1, n+1) runs from 1 to n. 5! = 120.
Factorial with recursion
Recursion means a function that calls itself with a smaller value.
def factorial(n):
if n == 0: # base case
return 1
return n * factorial(n - 1)
print(factorial(5))
factorial(5) becomes 5 × factorial(4), then 4 × factorial(3), down to factorial(0) which returns 1. Then the results multiply back up to 120.
Using math.factorial
For real code, Python already has a factorial function.
import math
print(math.factorial(5))
math.factorial is the fastest and safest choice. You write your own loop or recursion mainly to understand how it works.
Common mistakes
- Wrong range. Use
range(1, n+1); without+1you miss n itself. - Starting f at 0. Start at 1 — multiplying by 0 gives 0 forever.
- Missing the base case in recursion. Without
if n == 0: return 1, recursion never stops. - Recursion on huge numbers. Very large n can hit Python's recursion limit — use a loop or
math.factorial.
Summary
- Factorial n! is the product of all whole numbers from 1 to n.
- With a loop: start f at 1 and multiply by each i in
range(1, n+1). - With recursion:
n * factorial(n-1), base case0! = 1. - For real code, use
math.factorial(n). - Remember 0! = 1 and that factorials grow very fast.
Next, try the prime number program, or revise Python loops.
Frequently Asked Questions
What is a factorial?
What is the factorial of 0?
Loop or recursion — which is better for factorial?
Is there a built-in factorial in Python?
math.factorial(n) returns the factorial directly. It is the fastest and safest choice for real code — you only write your own loop or recursion to learn how it works.