Write a Recursive Factorial Function in Python
Define a recursive factorial function that handles edge cases and returns the product of all positive integers up to n.
Python code
10 linesdef factorial(n):
"""Return the factorial of n using recursion."""
if n < 0:
raise ValueError("Factorial is not defined for negative numbers")
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
if __name__ == "__main__":
print(factorial(5))
Output
120
How it works
The function checks for negative input and raises a ValueError to prevent invalid recursion. The base case returns 1 when n is 0 or 1, stopping the recursion. Each recursive call multiplies n by the factorial of n-1, breaking the problem into smaller subproblems. This works because every recursive call reduces n, so the base case is eventually reached. In the main block, factorial(5) returns 54321 = 120 and prints it.
Common mistakes
- Forgetting the base case, which causes infinite recursion and a RecursionError
- Not handling negative numbers, leading to infinite recursion with negative n
- Using an iterative loop instead of recursion, defeating the purpose
- Placing the base case after the recursive call, so it never executes
Variations
- Use functools.lru_cache to memoize results for repeated calls
- Write an iterative version using a loop for efficiency on large n
Real-world use cases
- Calculating permutations and combinations in probability and combinatorics scripts.
- Implementing recursive algorithms like generating permutations or combinations where factorial is a core step.
- Estimating factorials in statistical formulas such as probability mass functions for small n.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.