Factorial Using Recursion in Python
Recursion solves a problem by calling the same function with a smaller input until it reaches a base case.
What is Factorial Using Recursion?
Recursion solves a problem by calling the same function with a smaller input until it reaches a base case.
Calculate a factorial with a recursive Python function.
When should you use it?
- Practice problem solving and data structures.
- Process data when every algorithm step must be explicit.
- Prepare for programming exercises, exams, and interviews.
Example code
main.py
def factorial(number):
if number < 0:
raise ValueError("Factorial is undefined for negative numbers")
if number <= 1:
return 1
return number * factorial(number - 1)
print(factorial(6))
Expected output
720
How it works
The base case returns 1 for zero or one. Every other call multiplies n by the factorial of n minus one. The recursion depth is O(n).
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Try empty, single-item, and duplicate-value inputs.
- Print state after every step to observe the algorithm.
- Benchmark 100, 1,000, and 10,000 items, then compare another approach.