What is Recursion in Python: Simple Explanation and Example
recursion is when a function calls itself to solve smaller parts of a problem until it reaches a simple case. It helps break down complex tasks into easier steps by repeating the same process inside the function.How It Works
Recursion works like a set of nested boxes, where each box contains a smaller box inside it. The function keeps calling itself with a smaller or simpler input, moving closer to a basic case that it can solve directly. Once the simplest case is reached, the function stops calling itself and starts returning results back through each previous call.
Think of it like climbing down a ladder one step at a time until you reach the ground (the base case), then climbing back up while carrying the answers. This process helps solve problems that can be divided into similar smaller problems.
Example
This example shows a function that calculates the factorial of a number using recursion. The factorial of 5 (written as 5!) is 5 × 4 × 3 × 2 × 1 = 120.
def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) print(factorial(5))
When to Use
Use recursion when a problem can be broken down into smaller versions of itself, like searching through folders, calculating sequences, or solving puzzles. It is especially useful for tasks like traversing trees, exploring mazes, or working with mathematical formulas that repeat.
However, recursion should be used carefully because too many calls can slow down the program or cause errors if the base case is missing.
Key Points
- Recursion means a function calls itself to solve smaller parts of a problem.
- It needs a base case to stop calling itself and avoid infinite loops.
- Useful for problems that repeat in smaller steps, like factorial or tree traversal.
- Can be less efficient than loops if not used carefully.