Ever wondered how a single line of code can call itself over and over, like a never‑ending echo?

In simple words, a function is a mini‑program you can reuse, and recursion is when that mini‑program asks itself to do a smaller piece of the job until it’s done.

What is a Function in Python?

A function is a block of code that does a specific task. Think of it like a kitchen gadget – you press a button, and it mixes, chops, or blends for you. You can use it many times without rewriting the steps.

Defining a Function

We start a function with the def keyword (short for "define"). The name comes right after, followed by parentheses and a colon.

def greet(name):
    print("Hello, " + name + "!")

Here greet is the function name, and name is a parameter – a placeholder for the value you’ll give it later.

Calling a Function

To run the function, you "call" it by writing its name and giving a real value (an argument) inside the parentheses.

greet("Aven")  # prints: Hello, Aven!

Parameters and Return Values

Parameters let you feed data into a function. A function can also send data back using the return statement. It’s like borrowing a book (the argument) and then giving the library a receipt (the return value).

def add(a, b):
    return a + b

sum = add(5, 7)  # sum is now 12

Why Use Functions?

  • Save time – write once, use many times.
  • Make code tidy – break a big problem into bite‑size pieces.
  • Reduce errors – test each piece separately.

Recursion: Functions that Call Themselves

Recursion happens when a function solves a problem by calling itself with a smaller version of that problem. It sounds spooky, but it’s just a clever shortcut.

Key Parts of a Recursive Function

  • Base case – the simplest situation where the function stops calling itself.
  • Recursive call – the line where the function calls itself with a reduced input.

Let’s see a classic example: calculating factorials. The factorial of a number n (written n!) is the product of all positive integers up to n. For instance, 5! = 5×4×3×2×1 = 120.

def factorial(n):
    if n == 0:            # base case
        return 1
    else:
        return n * factorial(n-1)  # recursive call

When you ask for factorial(3), Python does this:

  • Is 3 zero? No → go to 3 * factorial(2)
  • Is 2 zero? No → go to 2 * factorial(1)
  • Is 1 zero? No → go to 1 * factorial(0)
  • Is 0 zero? Yes → return 1

Now the answers climb back up the “stack” and give you 6.

How Recursion Works – The Call Stack

Imagine a stack of plates. Each time a recursive call happens, a new plate (a function frame) is placed on top. When the base case hits, the plates start getting removed, each returning its value to the one below.

graph TD A[Start recursion] --> B[Check base case] B -->|No| C[Make recursive call] C --> B B -->|Yes| D[Return result] D --> E[Unwind stack] E --> F[Final answer]

Common Pitfalls

  • Missing base case: the function never stops and crashes.
  • Too deep recursion: Python’s default limit is about 1000 calls; exceeding it raises a RecursionError.
  • Unnecessary recursion: sometimes a simple loop is faster and clearer.

Quick Comparison: Iteration vs Recursion

AspectIteration (loops)Recursion
Typical useCounting, traversing arraysDivide‑and‑conquer problems (e.g., tree traversal)
MemoryConstant (just loop counter)Uses call stack – more memory
ReadabilityOften straightforwardCan be elegant for self‑similar tasks
RiskInfinite loop if condition wrongStack overflow if base case missing

📝 Likely Exam Questions

  1. Write a Python function to compute the nth Fibonacci number using recursion.
    def fib(n):
        if n 
  2. Explain the role of the base case in a recursive function.
    It tells the function when to stop calling itself. Without it, the function would call itself forever and cause a stack overflow.
  3. What will be the output of the following code?
    def foo(x):
        if x == 1:
            return 1
        return x + foo(x-1)
    print(foo(4))
    

    Answer: 10 (because 4+3+2+1 = 10).
  4. List two advantages of using functions in a Python program.
    1) Reusability – write once, call many times.
    2) Modularity – break complex problems into simpler parts, making debugging easier.
  5. Convert the iterative factorial code below into a recursive version.
    Iterative:
    def fact_iter(n):
        result = 1
        for i in range(1, n+1):
            result *= i
        return result
    
    Recursive answer:
    def fact_rec(n):
        if n == 0:
            return 1
        return n * fact_rec(n-1)
    
#CBSE#Class 12#Computer Science#Python#Functions#Recursion