Python Tutorial

Introduction to Recursive Functions

A recursive function is a function that calls itself in order to solve a problem. The idea behind recursion is to break down a complex problem into smaller, more manageable problems until you reach a solution.

 

Defining a Recursive Function

To create a recursive function, you need to include a call to the function within its own body. The function must also have a base case, which is a condition that stops the recursion. Here’s a simple structure for a recursive function:

def function_name(parameters):
    # Base case: condition to stop recursion
    if condition:
        # Stop the recursion
    else:
        # Recursive call
        function_name(parameters)
    # Other code

The base case ensures that the recursion will eventually end. Without it, the function would call itself indefinitely, leading to a RecursionError.

 

Python Recursive Function Examples

Example 1: Simple Recursive Function

Consider a function to perform a countdown from a specified number to zero:

def count_down(start):
    """ Count down from a number """
    print(start)

If you call count_down(3), it will only print 3. To achieve a countdown from 3 to 1, the function needs to call itself with a decremented value:

def count_down(start):
    """ Count down from a number """
    print(start)
    count_down(start-1)

Calling this function will result in a RecursionError because there is no base case to stop the recursion. To fix this, add a condition to stop when the countdown reaches zero:

def count_down(start):
    """ Count down from a number """
    print(start)
    next = start - 1
    if next > 0:
        count_down(next)

Output:

3
2
1

This version of count_down() only recurses when the next number is greater than zero, thus preventing an infinite loop.

 

Example 2: Calculating the Sum of a Sequence

To compute the sum of a sequence from 1 to n, you can use a for loop:

def sum(n):
    total = 0
    for index in range(n+1):
        total += index
    return total

Output for sum(100):

5050

To solve this using recursion, you can use the following approach:

def sum(n):
    if n > 0:
        return n + sum(n-1)
    return 0

Output for sum(100):

5050

Alternatively, using the ternary operator makes the function even more concise:

def sum(n):
    return n + sum(n-1) if n > 0 else 0

Output for sum(100):

5050

Summary

  • A recursive function is one that calls itself to break down a complex problem into simpler sub-problems.
  • Ensure that your recursive function has a base case to stop recursion, otherwise it will result in an error.
  • Recursive functions can often simplify problems that involve repetitive processes, like calculating sequences or traversing data structures.

Understanding recursion is crucial for solving complex problems in programming, especially when dealing with algorithms and data structures that naturally lend themselves to recursive solutions.