Can you explain the concept of recursion and provide an example of a recursive function you have implemented in Python?
Recursion is a programming technique where a function calls itself in order to solve a problem. It's often used for tasks that can be broken down into smaller, similar subproblems. Here's an example of a recursive function to calculate the factorial of a number:
def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) # Usage print(factorial(5)) # Output: 120
In this example, the factorial()
function calls itself with a smaller argument until it reaches the base case (n == 0
), then returns the result back through the call stack.