Numbers · beginner
Python Program to Find the Factorial of a Number
Find the factorial of a number in Python with a loop, with recursion and with math.factorial(), and see how recursive calls stack up in the visualizer.
- for loop
- recursion
- math.factorial()
- big integers
The factorial of n, written n!, is the product of all whole numbers from 1 to n: 5! = 5 × 4 × 3 × 2 × 1 = 120. By definition 0! is 1. Factorials count arrangements: there are 5! = 120 ways to order five books on a shelf.
Python integers have no fixed size, so factorials never overflow the way they do in C or Java: 20! still fits a 64-bit integer, but 25! does not, and Python prints it anyway.
The program
def factorial(n):
if n < 0:
raise ValueError("factorial is not defined for negative numbers")
result = 1
for i in range(2, n + 1):
result *= i
return result
print(factorial(5))
print(factorial(0))
print(factorial(25))120
1
15511210043330985984000000How it works
- Negative numbers have no factorial, so the function raises a ValueError with a clear message.
- result starts at 1, which is also the answer for 0 and 1 because the loop does not run for them.
- The loop multiplies result by 2, 3, … up to n. result *= i is short for result = result * i.
- factorial(25) shows Python's unlimited integers: the 26-digit result is exact.
Watch it run line by line
In the loop version watch result grow: 1, 2, 6, 24, 120. Then visualize the recursive version below: each call adds a new factorial frame with its own n, and the return values flow back up the stack.
“Visualize step by step” opens the program in the Python Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: Recursion and math.factorial()
The recursive version follows the mathematical definition n! = n × (n - 1)!. It is elegant but limited by the recursion limit (about 1,000 calls). math.factorial() is the fastest and should be your choice in real code.
import math
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
print(math.factorial(5))120
120Common mistakes
- Starting result at 0: anything multiplied by 0 stays 0.
- Using range(1, n), which stops at n - 1 and gives (n - 1)! instead of n!.
- A recursive version without a base case (if n <= 1) never stops and ends with RecursionError.
- Calling the recursive version with 5000 raises RecursionError; use the loop or math.factorial() for large n.
Try it yourself
- Print the factorials of 0 to 10 in a table.
- Count the trailing zeros of 100! (the answer is 24).
- Compute the number of ways to choose 3 items from 10 with factorials, then check it with math.comb(10, 3).
Open the program in the Python Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 Python examples, or write your own program in the online Python Compiler.