Ever wondered how a single line of code can call itself over and over? That's the magic of functions and recursion – and it shows up a lot in CBSE exams.
In simple words, a function is a reusable mini‑program that does a specific job. Recursion is when that mini‑program asks itself to do the same job on a smaller piece of the problem until it can finish easily.
Python functions for CBSE Class 12
What is a function?
A function is a block of code that runs only when you tell it to. Think of it like a kitchen appliance: you press the button (call the function) and it does its job (mix, blend, toast) without you having to repeat the steps each time.
Defining and calling a function
In Python you start a function with the keyword def (short for define). The name comes right after, then parentheses that may hold parameters (values the function needs).
def greet(name):
print("Hello, " + name + "!")
# calling the function
greet("Aven")
When greet("Aven") runs, the word name inside the function becomes "Aven" and the message prints.
Parameters and return values
Parameters are like placeholders. A return value (the word return tells Python to send a result back) is what you get after the function finishes.
def add(a, b):
return a + b
sum = add(5, 7) # sum now holds 12
Why use functions?
- Reusability: Write once, use many times.
- Readability: Break a big problem into bite‑size pieces.
- Testing: Check each piece separately.
Understanding recursion in Python
Recursion explained
Recursion is a function that calls itself. It sounds wild, but imagine a set of Russian dolls – each doll contains a smaller one until you reach the tiniest doll that can’t open any further. The smallest doll is the base case (the condition that stops the calling).
Base case and recursive case
Every recursive function needs two parts:
- Base case: When the problem is simple enough to solve directly.
- Recursive case: The part that reduces the problem and calls the function again.
Simple recursion 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 case
return n * factorial(n-1)
print(factorial(5)) # prints 120
Notice how the function keeps calling itself with a smaller number (n‑1) until it reaches 0.
Recursion vs iteration
Iteration uses loops (like for or while) to repeat work. Recursion relies on the call stack – the place Python stores each function call.
| Aspect | Recursion | Iteration |
|---|---|---|
| Typical use | Problems that naturally shrink (tree traversal, factorial) | Simple counting loops |
| Memory | Uses call stack; can cause stack overflow for deep recursion | Uses constant memory |
| Readability | Often clearer for divide‑and‑conquer tasks | Sometimes harder to follow when many indices are involved |
How recursion works – a flowchart
📝 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 call itself forever and cause a stack overflow. - Convert the following recursive function into an iterative one:
def sum_n(n): return n + sum_n(n-1) if n>0 else 0.
Model answer:def sum_n_iter(n): total = 0 while n > 0: total += n n -= 1 return total - What will be the output of the code snippet below and why?
def foo(x): if x == 1: return 1 return x * foo(x-1) print(foo(3))
Model answer: It prints 6 because foo(3) = 3 * foo(2), foo(2) = 2 * foo(1), and foo(1) returns 1. Multiplying gives 3×2×1 = 6. - List two advantages of using functions in Python programs.
Model answer: (i) They avoid code repetition, and (ii) they make programs easier to read and debug.