Ever wondered how a single line of code can repeat itself without a loop? That's the magic of functions and recursion.
💡 In Simple Words: A function is a mini‑program you can call whenever you need it. Recursion is when that mini‑program asks itself to do a smaller piece of the job until it’s done.
What are Python Functions?
A function is a reusable block of code that does a specific job. Think of it like a kitchen appliance: you press the same button, and it mixes, chops, or blends every time.
Why use a function?
- Save typing – write once, use many times.
- Make code easier to read.
- Break big problems into smaller pieces.
How to Write a Function in Python
First time you see the word def (short for define), it tells Python, “Hey, I’m creating a new function.” The basic shape looks like this:
def function_name(parameters):
# code block
return result
Example: a function that adds two numbers.
def add(a, b):
return a + b
sum = add(3, 5) # sum becomes 8
Notice the return keyword sends a value back to where the function was called.
Recursion: Functions Calling Themselves
Recursion is when a function solves a problem by calling itself with a smaller piece of the same problem. Imagine Russian nesting dolls: each doll contains a smaller one until you reach the tiniest doll that can’t be opened. That tiniest doll is the base case – the condition that stops the recursion.
Simple factorial example
def factorial(n):
if n == 0: # base case
return 1
else:
return n * factorial(n-1) # recursive call
If you ask for factorial(3), Python does:
- factorial(3) → 3 * factorial(2)
- factorial(2) → 2 * factorial(1)
- factorial(1) → 1 * factorial(0)
- factorial(0) → 1 (base case)
Multiplying the returned values gives 6.
How Recursion Works – Call Stack
Every time the function calls itself, Python puts a new “frame” on a stack (think of a stack of plates). When the base case is hit, plates start getting removed, returning values back up.
When to Choose Recursion over Loops
- Problem naturally fits a “divide‑and‑conquer” pattern (e.g., tree traversals, binary search).
- You need a clear, short description rather than many loop counters.
- Memory isn’t a concern – each call uses extra space.
Common Mistakes
- Forgetting the base case – leads to infinite recursion and a crash.
- Using recursion for very large inputs – can hit the recursion limit.
- Returning inside the recursive call incorrectly – may give wrong results.
Quick Summary
| Concept | Key Point |
|---|---|
| Function | Reusable code block defined with def. |
| Return | Sends a value back to the caller. |
| Recursion | Function calls itself until a base case stops it. |
| Base case | Condition that ends the recursive calls. |
| Call stack | Memory structure that holds active function calls. |
📝 Likely Exam Questions
- Write a Python function to compute the nth Fibonacci number using recursion.
Answer:def fib(n): if n - Explain the role of the base case in recursion with an example.
Answer: The base case stops further self‑calls. In factorial,if n == 0: return 1prevents infinite calls. - What will be the output of the following code?
def foo(x): if x > 1: return foo(x-1) + x return 1 print(foo(3))
Answer: 6 (calculation: foo(3)=foo(2)+3; foo(2)=foo(1)+2; foo(1)=1 → 1+2+3=6.) - List two advantages of using recursion over an iterative loop.
Answer: (1) Code can be more readable for problems like tree traversal. (2) It matches the mathematical definition of many sequences. - How can you avoid a “maximum recursion depth exceeded” error?
Answer: Ensure a proper base case, limit input size, or convert the algorithm to an iterative version.