Why bother with functions and recursion?
Imagine you have to tell a friend how to bake a cake. Would you repeat the whole recipe every time you bake? Of course not—you’d write it down once and follow the steps. Python functions are the same idea: write a piece of code once, then reuse it whenever you need.
💡 In Simple Words: A function is a named block of code you can call again and again. Recursion is when a function calls itself to solve a smaller piece of the same problem, like breaking a big puzzle into tiny ones.
What is a Python Function?
Function means a reusable chunk of code that does a specific job. You give it a name, tell Python what inputs (called parameters) it needs, and optionally tell it to give back a result (called a return value).
Defining a Function
Use the def keyword, then the name, parentheses, and a colon. Inside, indent the statements.
def greet(name):
print("Hello, " + name + "!")
Calling a Function
Just write the name followed by parentheses, putting any arguments inside.
greet("Aven") # prints: Hello, Aven!Parameters and Return Values
Parameters let you feed data into the function. The return statement sends a value back to the caller.
def add(a, b):
return a + b
sum = add(5, 7) # sum is now 12Why Use Functions?
- Readability: Code is easier to follow when each part has a clear name.
- Reusability: Write once, use many times—no copy‑paste errors.
- Testing: Small pieces are simpler to test individually.
Understanding Recursion
Recursion is a technique where a function solves a problem by calling itself with a smaller version of that problem. Think of Russian nesting dolls: each doll contains a smaller one, and you keep opening them until you reach the tiniest doll.
Two Key Parts of Every Recursive Function
- Base case: The condition that stops the recursion. Without it, the function would call itself forever.
- Recursive step: The part where the function calls itself with a simpler input.
Simple Example: Factorial
The factorial of a number n (written n!) is the product of all positive integers up to n. For example, 5! = 5×4×3×2×1 = 120.
def factorial(n):
if n == 0: # base case
return 1
else: # recursive step
return n * factorial(n-1)
When you call factorial(4), Python does this:
Common Recursive Patterns
Besides factorial, recursion shines in problems like:
- Fibonacci numbers: each number is the sum of the two before it.
- String reversal: put the last character first, then reverse the rest.
- Tree traversal: visit a node, then its children, using the same logic for each subtree.
When Not to Use Recursion
Recursion can be elegant, but it uses extra memory for each call (the call stack). For very deep recursion, you might hit Python’s recursion limit (default 1000). In such cases, an iterative loop (using while or for) is safer.
Function vs Recursion – Quick Comparison
| Aspect | Regular Function | Recursive Function |
|---|---|---|
| How it solves | Performs the whole task in one go. | Breaks the task into smaller identical tasks. |
| Memory use | Usually constant. | Uses call stack; grows with depth. |
| Readability | Straightforward for simple tasks. | Often clearer for problems with self‑similar structure. |
| Risk | Few pitfalls. | Must have a correct base case to avoid infinite loops. |
Tips to Master Functions & Recursion
- Write the base case first—think of it as the “stop” sign.
- Trace the function on paper with small inputs before coding.
- Use descriptive names for functions and parameters; they act like labels on a recipe.
- Test edge cases such as
n = 0or empty strings.
📝 Likely Exam Questions
- Write a function
is_palindrome(s)that returns True if the stringsis a palindrome using recursion.
Model answer:def is_palindrome(s): if len(s) - Explain the role of the base case in a recursive function.
Model answer: The base case stops further self‑calls by providing a direct answer for the simplest input. Without it, the function would call itself forever and eventually cause a stack overflow. - Given the function below, what is the output of
mystery(3)?
Model answer: The function returns the sum of numbers from 1 to 3, sodef mystery(n): if n == 1: return 1 return n + mystery(n-1)mystery(3)yields 6. - Differentiate between iteration and recursion with an example.
Model answer: Iteration uses loops (e.g.,for i in range(5):) to repeat actions, while recursion calls the same function inside itself (e.g., factorial). Both can compute the same result, but recursion relies on the call stack. - What will happen if a recursive function lacks a proper base case?
Model answer: The function will keep calling itself until Python reaches its recursion depth limit, raising aRecursionError.