Why are functions and recursion worth your time?
Imagine you could ask a tiny robot to do a math trick for you, and then ask that same robot to call a smaller version of itself to finish the job. That’s what Python functions and recursion let you do – they turn messy code into neat, reusable pieces.
💡 In Simple Words: A function is like a tiny robot that does a job whenever you ask it. Recursion is when that robot calls itself to solve a smaller piece of the problem, kind of like a set of Russian dolls.
What is a Python function?
Definition
A function is a block of code that runs only when you tell it to. In Python you start a function with the def keyword, give it a name, optional parameters (the inputs), and end with a return statement that sends a result back.
How to write a simple function
Here’s a tiny function that adds two numbers:
def add(a, b):
result = a + b
return result
When you call add(3, 5) Python jumps into the function, stores a=3 and b=5, computes result, and then hands the value 8 back to the place where you called it.
Why use functions?
- **Reuse** – write once, use many times.
- **Readability** – a well‑named function tells you what the code does without reading every line.
- **Testing** – you can check a single function in isolation.
Understanding recursion
Definition
Recursion is a special kind of function that solves a problem by calling itself with a simpler version of that problem. Think of it as a set of nesting dolls: each doll opens to reveal a smaller one until you reach the tiniest doll that can’t open any further.
Base case and recursive case
Every recursive function needs two parts:
- Base case – the condition that stops the recursion. Without it, the function would call itself forever.
- Recursive case – the part that calls the same function again, but with a reduced input.
Worked example: factorial
The factorial of a number n (written n!) multiplies all positive integers up to n. For example, 5! = 5×4×3×2×1 = 120. A recursive definition looks like this:
def factorial(n):
if n == 0: # base case
return 1
else: # recursive case
return n * factorial(n-1)
Let’s walk through factorial(3):
- Is
nzero? No, so go to the recursive case. - Return
3 * factorial(2). - To compute
factorial(2), repeat the steps:2 * factorial(1). - Again:
1 * factorial(0). - Now
nis zero, so return1. - Unwind:
1 → 1*1 = 1, then2*1 = 2, then3*2 = 6. The final answer is6.
When to choose recursion over loops
Both loops (like for or while) and recursion can solve the same problems, but one may be clearer or more efficient depending on the situation. The table below helps you decide.
| Aspect | Loop | Recursion |
|---|---|---|
| Memory usage | Constant (just a counter) | Uses call stack; each call adds a frame |
| Readability for hierarchical data | Can become messy | Very natural (e.g., tree traversals) |
| Risk of infinite execution | Depends on loop condition | Depends on missing base case |
| Typical use cases | Counting, simple aggregations | Factorial, Fibonacci, file‑system walks |
Common pitfalls
- Forgetting the base case – leads to a stack overflow error.
- Using mutable default arguments – can cause unexpected sharing of data between calls.
- Excessive recursion depth – Python’s default limit is about 1000 calls; deep problems need tail‑recursion tricks or an iterative rewrite.
📝 Likely Exam Questions
- Q1. Write a Python function to compute the nth Fibonacci number using recursion.
Ans:def fib(n): if n - Q2. Explain the role of the base case in a recursive function.
Ans: The base case stops further self‑calls. It provides a direct answer when the problem is small enough, preventing infinite recursion and allowing the call stack to unwind. - Q3. Compare the time complexity of the recursive factorial function with an iterative version.
Ans: Both have O(n) time, but the recursive version uses O(n) extra stack space, while the iterative version uses O(1) extra space. - Q4. Identify the error in the following code and correct it:
def sum_digits(n): if n == 0: return 0 else: return n % 10 + sum_digits(n)
Ans: The recursive call should usen//10to reduce the number:return n % 10 + sum_digits(n//10). - Q5. When is it preferable to use a recursive approach for tree traversal?
Ans: When the data naturally forms a hierarchical structure (like a binary tree), recursion mirrors the tree’s shape, making the code shorter and easier to understand.