Lesson 38 of 70 – Recursion
54%

Python Recursion

Recursion is a programming technique in which a function calls itself to solve a problem. A recursive function keeps calling itself until a base condition is reached.

Note: Every recursive function should have a condition that stops the recursion. This condition is called the base case.
What is Recursion?

Recursion means that a function calls itself from inside its own definition.

Basic structure:

def function():
    function()

However, the function must have a condition to stop calling itself.

Simple Recursive Function
def message(n):

    if n == 0:
        return

    print("Hello")
    message(n - 1)

message(3)
Output:
Hello
Hello
Hello

The function calls itself with a smaller value each time. When n becomes 0, the function stops.

Base Case

The base case is the condition that stops a recursive function.

def count(n):

    if n == 0:
        return

    print(n)
    count(n - 1)

count(5)
Output:
5
4
3
2
1

Here, if n == 0: is the base case.

Recursive Case

The recursive case is the part of the function where the function calls itself.

def count(n):

    if n == 0:
        return

    print(n)

    # Recursive case
    count(n - 1)

The statement count(n - 1) is the recursive case.

Recursion Example: Countdown
def countdown(n):

    if n == 0:
        print("Done")
        return

    print(n)
    countdown(n - 1)

countdown(5)
Output:
5
4
3
2
1
Done
Factorial Using Recursion

The factorial of a number is the product of all positive integers from that number down to 1.

For example:

5! = 5 × 4 × 3 × 2 × 1 = 120

Python example:

def factorial(n):

    if n == 0:
        return 1

    return n * factorial(n - 1)

print(factorial(5))
Output:
120
How Factorial Recursion Works

When we call:

factorial(5)

Python evaluates it like this:

5 × factorial(4)
5 × 4 × factorial(3)
5 × 4 × 3 × factorial(2)
5 × 4 × 3 × 2 × factorial(1)
5 × 4 × 3 × 2 × 1

The final result is 120.

Sum of Numbers Using Recursion
def total(n):

    if n == 0:
        return 0

    return n + total(n - 1)

print(total(5))
Output:
15

The calculation is: 5 + 4 + 3 + 2 + 1 = 15.

Recursive Fibonacci Function

The Fibonacci sequence starts with 0 and 1. Each following number is the sum of the previous two numbers.

def fibonacci(n):

    if n <= 1:
        return n

    return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(6))
Output:
8
Print Fibonacci Series Using Recursion
def fibonacci(a, b, count):

    if count == 0:
        return

    print(a)

    fibonacci(b, a + b, count - 1)

fibonacci(0, 1, 7)
Output:
0
1
1
2
3
5
8
Reverse a String Using Recursion
def reverse(text):

    if text == "":
        return text

    return reverse(text[1:]) + text[0]

print(reverse("Python"))
Output:
nohtyP
Find Power Using Recursion
def power(base, exponent):

    if exponent == 0:
        return 1

    return base * power(base, exponent - 1)

print(power(2, 5))
Output:
32

This calculates 2⁵ = 32.

Recursion with Lists
def print_list(items, index):

    if index == len(items):
        return

    print(items[index])

    print_list(items, index + 1)

numbers = [10, 20, 30, 40]

print_list(numbers, 0)
Output:
10
20
30
40
Recursive Function with Multiple Parameters

A recursive function can have more than one parameter.

def display(start, end):

    if start > end:
        return

    print(start)

    display(start + 1, end)

display(1, 5)
Output:
1
2
3
4
5
Recursion and Call Stack

When a recursive function calls itself, Python keeps track of each function call using the call stack.

Each new call is placed on the stack. When the base case is reached, the calls return one by one.

def count(n):

    if n == 0:
        return

    print(n)
    count(n - 1)

count(3)

The calls are approximately:

count(3) → count(2) → count(1) → count(0)
What Happens Without a Base Case?

If a recursive function never reaches a stopping condition, it continues calling itself.

def example():
    example()

example()

This causes Python to eventually raise a RecursionError.

Important: Always make sure that a recursive function can eventually reach its base case.
RecursionError

Python limits how deeply ordinary recursive calls can continue. If that limit is exceeded, Python raises RecursionError.

def test():
    test()

test()
Result:
RecursionError
Recursion vs Loop

Using a loop:

for i in range(1, 6):
    print(i)

Using recursion:

def display(i):

    if i > 5:
        return

    print(i)
    display(i + 1)

display(1)

Both can produce the same output, but they use different approaches. Loops are often simpler for straightforward repetition, while recursion can be useful for problems that naturally break into smaller versions of the same problem.

When Should You Use Recursion?
  • When a problem can naturally be divided into smaller similar problems.
  • When working with tree-like data structures.
  • When solving certain searching and sorting problems.
  • When the recursive solution is easier to understand than an iterative solution.
  • When each recursive step moves clearly toward a base case.
Advantages of Recursion
  • Can make some complex problems easier to understand.
  • Works naturally with hierarchical data.
  • Can produce concise solutions for some problems.
  • Useful in algorithms such as tree traversal and divide-and-conquer algorithms.
Disadvantages of Recursion
  • Recursive calls use additional call-stack space.
  • Too many recursive calls can cause RecursionError.
  • Some recursive solutions are slower than suitable iterative solutions.
  • Recursive code can be difficult for beginners to trace.
  • A missing or incorrect base case can cause problems.
Important Recursion Terms
Term Meaning
Recursion A function calling itself.
Base Case The condition that stops recursion.
Recursive Case The part that calls the function again.
Call Stack Memory structure used to keep track of active function calls.
RecursionError Error raised when recursive calls become too deep.
Key Points
  • Recursion occurs when a function calls itself.
  • A recursive function needs a base case.
  • The recursive case performs another function call.
  • Factorial and Fibonacci are common examples of recursion.
  • Recursive calls are tracked using the call stack.
  • Missing or unreachable base cases can cause RecursionError.
  • Recursion is especially useful for problems with naturally recursive structures.

🧠 Quick Quiz

Question: What is the purpose of a base case in recursion?