Last modified: Nov 16, 2026
Python Factorial Program with Examples
The factorial of a number is a classic programming exercise. It helps you practice loops, recursion, and functions. In this article, you will learn how to write a Python factorial program in several ways. Each method includes example code and output. This makes it easy to follow along, even if you are a beginner.
By the end, you will know how to compute factorials using a for loop, a while loop, recursion, and the built-in math.factorial function. You will also learn how to handle edge cases and avoid common mistakes.
What Is a Factorial?
The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is written as n!.
For example, 5! = 5 × 4 × 3 × 2 × 1 = 120. By definition, 0! = 1. Factorials grow very fast. Even 10! is 3,628,800.
Factorials appear in combinatorics, probability, and algorithm analysis. They are also a great way to understand how loops and recursion work in Python.
Method 1: Using a for Loop
The most straightforward way to compute a factorial is with a for loop. You start with a result of 1 and multiply it by each number from 1 to n.
def factorial_loop(n):
# Start with 1 because multiplying by 1 changes nothing
result = 1
# Loop from 1 up to and including n
for i in range(1, n + 1):
result *= i
return result
# Test the function
print(factorial_loop(5)) # 120
print(factorial_loop(0)) # 1
print(factorial_loop(7)) # 5040
120
1
5040
This approach is easy to read and works well for small to moderate values of n. The range function generates numbers from 1 to n inclusive. The result variable accumulates the product.
If you want to compare this with other number checks, you might also enjoy our guide on the Python prime number check program. Both examples show how loops solve classic number problems.
Method 2: Using a while Loop
A while loop gives you more control over the counter. This can be useful when you want to decrement from n down to 1.
def factorial_while(n):
result = 1
# Multiply result by n, then decrease n by 1
while n > 1:
result *= n
n -= 1
return result
print(factorial_while(6)) # 720
print(factorial_while(1)) # 1
720
1
The loop stops when n reaches 1. Since multiplying by 1 does not change the result, this is correct. This version is slightly shorter than the for loop version.
Method 3: Using Recursion
Recursion is a natural fit for factorials. The mathematical definition is recursive: n! = n × (n-1)! with the base case 0! = 1.
def factorial_recursive(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
# Recursive case: n * factorial(n-1)
return n * factorial_recursive(n - 1)
print(factorial_recursive(4)) # 24
print(factorial_recursive(0)) # 1
24
1
Recursion makes the code elegant. However, Python has a default recursion limit (usually 1000). So for very large n, recursion can raise a RecursionError. Use recursion for small inputs or when clarity matters more than performance.
If you are new to function parameters, our guide on Python function arguments explained can help you understand how arguments are passed into these factorial functions.
Method 4: Using the math Module
Python's standard library includes a built-in factorial function in the math module. It is fast, reliable, and handles large numbers efficiently.
import math
print(math.factorial(5)) # 120
print(math.factorial(10)) # 3628800
print(math.factorial(0)) # 1
120
3628800
1
This is the recommended approach for production code. It avoids manual loops and recursion. It also raises a ValueError if you pass a negative number or a non-integer.
Handling Edge Cases and Errors
Good factorial functions should handle invalid input. Negative numbers do not have a factorial in the standard definition. Non-integers should also be rejected.
def safe_factorial(n):
# Check for negative numbers
if n < 0:
raise ValueError("Factorial is not defined for negative numbers")
# Check for non-integers
if not isinstance(n, int):
raise TypeError("Factorial requires an integer")
result = 1
for i in range(1, n + 1):
result *= i
return result
try:
print(safe_factorial(-3))
except ValueError as e:
print("Error:", e)
Error: Factorial is not defined for negative numbers
Adding validation makes your program more robust. This is a good habit when writing reusable functions.
Factorial with Large Numbers
Python integers have arbitrary precision. That means you can compute factorials of large numbers without overflow. For example, 100! has 158 digits.
import math
big = math.factorial(100)
print(len(str(big))) # Number of digits
print(str(big)[:10]) # First 10 digits
158
9332621544
When displaying such numbers, you may want to format them nicely. Our article on Python round to 2 decimal places covers formatting techniques that can help with presentation.
Comparing the Methods
Each method has trade-offs. The for loop is simple and efficient. The while loop is slightly more compact. Recursion is elegant but limited by stack depth. The math.factorial function is the fastest and safest for real projects.
For learning purposes, write all three versions. It builds your understanding of loops and recursion. Then use math.factorial in production code.
Common Mistakes to Avoid
Beginners often forget that 0! = 1. Others start their loop at 0, which zeroes out the result. Also, be careful with recursion depth for large inputs.
Another mistake is not validating input. Always check for negative numbers and non-integers if your function is user-facing.
Conclusion
Writing a Python factorial program is a great way to practice core programming skills. You have seen four approaches: for loop, while loop, recursion, and the math module. Each has its place.
Start with the loop version to understand the logic. Try recursion to learn about base cases. Then use math.factorial for real-world code. With these examples, you can confidently compute factorials in any Python project.