Junior — Middle
Can you explain how recursive functions work in Python?
sobes.tech AI
Answer from AI
A recursive function in Python is a function that calls itself to solve a problem by breaking it down into simpler subproblems. Recursion is typically used for problems that naturally divide into similar subproblems, such as calculating factorials, traversing trees, or searching graphs.
Working principle:
- The function calls itself with a modified argument.
- Each call creates a new frame in the call stack.
- Recursion must have a base case (exit condition) to avoid infinite calls.
Example of calculating factorial:
def factorial(n):
if n == 0:
return 1 # base case
else:
return n * factorial(n - 1) # recursive call
print(factorial(5)) # Outputs 120
Here, factorial(5) calls factorial(4), then factorial(3), and so on until factorial(0), after which the values are returned up the call stack.