The Two Core Rules of Recursion
Every recursive function must have two essential parts:- Base Case: The stopping condition. This is the simplest possible case that can be answered directly without calling the function again. Without a base case, the function will call itself forever!
- Recursive Case: The part of the function where it calls itself with a modified, smaller input, moving closer to the base case.
Example 1: Countdown
Let’s look at a simple function that counts down to zero.How it executes:
countdown(3)is called. Prints3. Callscountdown(2).countdown(2)is called. Prints2. Callscountdown(1).countdown(1)is called. Prints1. Callscountdown(0).countdown(0)is called. Since0 <= 0, it matches the base case, prints"Blast off! 🚀", and returns. All function calls finish execution.
Example 2: Factorial
In mathematics, the factorial of a positive integer (written as ) is the product of all positive integers less than or equal to . For example: . Mathematically, we can define it recursively:- (Base Case)
- (Recursive Case)
Visualizing the trace:
Example 3: Fibonacci Sequence
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones:0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Precautions & Common Pitfalls
1. Infinite Recursion (RecursionError)
If a recursive function never reaches its base case, it keeps calling itself until Python reaches its maximum call stack depth limit and crashes.
2. Performance Overhead
Each recursive call is added to the system’s “call stack” in memory. If the recursion is too deep (e.g., thousands of calls), it uses a lot of memory. For example, calculatingfibonacci(40) using the simple recursive function above is extremely slow because it recalculates the same values millions of times. In such cases, an iterative loop (for or while) or caching (memoization) is preferred.
What’s next?
Now that you have completed all function concepts, test and reinforce your understanding with hands-on practice problems.Practice & Exercises
Practice writing and debugging functions