Recursion is a programming technique where a function calls itself to solve a problem. A recursive function generally has two main components:
1. Base Case: This stops the recursion when a certain condition is met.
2. Recursive Case: This part breaks the problem down into smaller instances of the same problem and makes a recursive call.
Example: recursive function to calculate the factorial of a number
def factorial(n):
# Base case: if n is 1 or 0, return 1
if n == 0 or n == 1:
return 1
# Recursive case: n * factorial of (n-1)
else:
return n * factorial(n - 1)
# Example usage:
print(factorial(5)) # Output will be 120
Explanation:
The base case is when n == 0
or n == 1
, which returns 1.
The recursive case reduces the problem by calling factorial(n-1)
.