Why learn Python functions and recursion?
Imagine you could write a recipe once and reuse it every time you need a chocolate cake – that’s what functions do for code. And what if the recipe could call itself to make a layered cake? That’s recursion, and both show up a lot in CBSE board exams.
In simple words, a function is a named set of instructions you can run whenever you want. Recursion is when that function runs itself, usually to break a big problem into smaller, similar pieces.
What is a function?
A function is like a mini‑program inside your program. You give it a name, tell it what to do, and later you can "call" it by that name. The first time you see the word define (to set up) a function, think of writing a recipe card.
Defining and calling a function
In Python you start a function with the def keyword (short for define). Then you write the name, parentheses, and a colon. The code that belongs to the function is indented underneath.
def greet(name):
print("Hello, " + name + "!")
To use it, you call it – just write the name followed by parentheses and any needed values (called arguments).
greet("Aven") # prints: Hello, Aven!Parameters and arguments
The words inside the parentheses when you define a function are parameters. They are placeholders that will receive real values (arguments) when you call the function. Think of parameters as empty seats at a dinner table; the arguments are the guests who sit down.
Return statement
Sometimes you want a function to give you a result back, not just print something. The return keyword sends a value back to the place where the function was called.
def add(a, b):
return a + b
sum = add(4, 5) # sum now holds 9Recursion – a function calling itself
Recursion is like those Russian nesting dolls that open to reveal a smaller copy of themselves. A recursive function solves a problem by solving a smaller version of the same problem, then stitching the answers together.
The key ingredients are:
- Base case: a condition that stops the recursion, like reaching the smallest doll.
- Recursive call: the function calls itself with a simpler input.
Classic example: factorial (n!) – the product of all positive integers up to n.
def fact(n):
if n == 1: # base case
return 1
else:
return n * fact(n-1) # recursive callWhen you ask for fact(4), Python does this:
- 4 * fact(3)
- 4 * (3 * fact(2))
- 4 * (3 * (2 * fact(1)))
- 4 * (3 * (2 * 1)) = 24
When to use recursion
- Problems that naturally break into similar sub‑problems (e.g., tree traversals, Fibonacci numbers).
- When a clear base case and a smaller sub‑problem are easy to define.
- When you want concise code and don’t mind extra memory for the call stack.
Common pitfalls
- Forgetting the base case – leads to infinite recursion and a crash.
- Using recursion for very large inputs – Python’s call stack is limited, causing a
RecursionError. - Mixing up return values – always return the result of the recursive call, not just print it.
Iteration vs Recursion – quick comparison
| Aspect | Iteration (loops) | Recursion |
|---|---|---|
| Typical use | Counting, simple repeats | Divide‑and‑conquer, tree structures |
| Memory | Constant (just loop counters) | Extra stack frames for each call |
| Readability | Often straightforward | Can be cleaner for hierarchical problems |
| Risk of error | Off‑by‑one bugs | Missing base case → infinite loop |
📝 Likely Exam Questions
- Write a Python function to compute the nth Fibonacci number using recursion.
Model answer:def fib(n): if n - Explain the role of the base case in a recursive function.
Model answer: The base case stops the recursion by providing a direct answer for the smallest sub‑problem. Without it the function would keep calling itself forever. - Given the function below, what is the output of
foo(3)?
Model answer:def foo(x): if x == 0: return 1 return x * foo(x-1) # foo(3) returns 6 - Convert the following iterative code to a recursive version:
Model answer:# Iterative sum def iter_sum(n): total = 0 for i in range(1, n+1): total += i return total # Recursive sum def rec_sum(n): if n == 0: return 0 return n + rec_sum(n-1)