Welcome to the “Recursion” tutorial!
Overview
A recursive function calls itself to solve smaller instances of a problem.
Base Case & Recursive Case
- Base Case: stops recursion.
- Recursive Case: divides problem and calls itself.
Example: Factorial
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1) # recursive case
print(factorial(5)) # 120
Key Takeaways
- Every recursive function needs a base case.
- Watch out for deep recursion to avoid
RecursionError
.
Happy coding!
Comments
Post a Comment