Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Create Recursive Functions in Python



Recursion is a process where a function calls itself repeatedly with new input values, slowly moving toward a condition where it stops.

This stopping condition is called the base case. It prevents the function from running endlessly and allows it to return a final result. In Python, we can create recursive functions by simply defining a function that calls itself.

Every recursive function has two main components ?

  • Recursive Case: This is when the function calls itself to solve a smaller part of the problem. It keeps the process going.
  • Base Case: This is the stopping point. It tells the function when to stop calling itself. Without it, the function would keep calling itself infinitely and lead to a stack overflow error.

Why use recursion?

Recursion provides a logical way to solve problems such as ?

  • Performing operations on hierarchical or nested data structures (like trees, graphs, etc.)
  • Solving mathematical problems like factorial, Fibonacci numbers, etc.
  • Implementing algorithms such as Depth-First Search (DFS), QuickSort, etc.

Recursion can make your code look neat and simple, but it is very important to make sure it doesn't go on forever. To stop it at the right time, you need to add a proper base case.

Creating a Recursive Function in Python

To create a recursive function in Python, we define a function that calls itself during its execution. This allows the function to repeat its behavior on smaller parts of the problem. Recursive functions are useful when a problem can be divided into similar sub-problems.

In Python, we can write a recursive function by setting up a base case to stop the recursion and a recursive case to continue it.

Calculating Factorial Using Recursion

The factorial of a number n, denoted as n!, is the product of all positive integers from 1 to n. For example ?

  • 5! = 5 × 4 × 3 × 2 × 1 = 120
  • 4! = 4 × 3 × 2 × 1 = 24
  • 1! = 1
  • 0! = 1 (by definition)

We can define this process using recursion, where the function calls itself with a smaller number each time, as shown below ?

  • factorial(0) = 1: This is the base case. We stop the recursion when n is 0.
  • factorial(n) = n × factorial(n - 1): This is the recursive case. The function multiplies n with the factorial of (n - 1).

In simpler words, the function keeps calling itself with smaller values (n - 1, n - 2, ...) until it reaches 0, and then the results are multiplied as the function returns step by step.

Example

In the following example, we are using a recursive function to calculate the factorial of a number ?

# Function to calculate factorial using recursion
def factorial(n):
   if n == 0:
      # base case
      return 1   
   else:
      # recursive call
      return n * factorial(n - 1)   

# Test the function
print("Factorial of 5 is:", factorial(5))

Following is the output obtained ?

Factorial of 5 is: 120

Fibonacci Sequence Using Recursion

The Fibonacci sequence is a series of numbers where each number is the sum of the two numbers before it. The sequence starts from 0 and 1, and then continues like this ?

0, 1, 1, 2, 3, 5, 8, 13, 21, ...

Here,

  • The first number is 0
  • The second number is 1
  • The third number is 0 + 1 = 1
  • The fourth number is 1 + 1 = 2
  • The fifth number is 1 + 2 = 3
  • And so on...

We can define this pattern recursively using the following rules ?

  • fibonacci(0) = 0: This is the base case for the 0th number.
  • fibonacci(1) = 1: This is the base case for the 1st number.
  • For any number n ? 2, we use fibonacci(n) = fibonacci(n - 1) + fibonacci(n - 2). This means the nth Fibonacci number is the sum of the previous two numbers.

In simple terms, the function keeps calling itself to calculate the two numbers before the current one until it reaches 0 or 1, where it stops.

Example

In the example below, we are using a recursive function to calculate the nth Fibonacci number ?

# Function to return nth Fibonacci number
def fibonacci(n):
   if n <= 1:
      # base case
      return n   
   else:
      # recursive case
      return fibonacci(n - 1) + fibonacci(n - 2)   

# Print the first 6 Fibonacci numbers
for i in range(6):
   print(fibonacci(i), end=" ")

We get the output as shown below ?

0 1 1 2 3 5 

Sum of Natural Numbers Using Recursion

To calculate the sum of the first n natural numbers (1, 2, 3, ..., n), we can use a recursive approach. This means we can break the problem down into smaller parts by adding one number at a time. For example ?

  • Sum of first 3 natural numbers = 1 + 2 + 3 = 6
  • Sum of first 5 natural numbers = 1 + 2 + 3 + 4 + 5 = 15

We can define this problem recursively as ?

  • sum(1) = 1: This is the base case. If n is 1, the sum is 1 and recursion stops here.
  • sum(n) = n + sum(n - 1): This is the recursive case. The function adds the current number n to the sum of all numbers before it.

In simple words, the function keeps calling itself with (n - 1) until it reaches 1. Then, the results are added step by step as the function returns.

Example

In the following example, we are using a recursive function to calculate the sum of the first n natural numbers ?

# Recursive function to calculate sum of first n natural numbers
def sum_natural(n):
   if n == 1:
      return 1
   else:
      return n + sum_natural(n - 1)

# Calculate the sum of first 5 numbers
print("Sum is:", sum_natural(5))

Following is the output of the above code ?

Sum is: 15

GCD of Two Numbers Using Recursion

The Greatest Common Divisor (GCD) of two numbers is the largest number that can divide both numbers exactly without leaving any remainder. For example ?

  • GCD of 12 and 8 is 4
  • GCD of 20 and 5 is 5
  • GCD of 7 and 3 is 1

We can find the GCD using a recursive method known as the Euclidean Algorithm. This method keeps reducing the problem into smaller values by taking the remainder until it becomes zero. The recursive logic is defined as ?

  • gcd(a, b) = gcd(b, a % b): This is the recursive case. We replace the pair with (b, a % b) and continue.
  • gcd(a, 0) = a: This is the base case. When the second number becomes 0, the first number is the GCD.

In simple terms, the function keeps calling itself with smaller values until the second number becomes 0. At that point, the first number is the answer.

Example

In this example, we are using a recursive function to find the Greatest Common Divisor (GCD) of two numbers using the Euclidean Algorithm ?

# Recursive function to find GCD of two numbers
def gcd(a, b):
   if b == 0:
      # base case
      return a   
   else:
      # recursive case
      return gcd(b, a % b)   

# Test the function
print("GCD of 48 and 18 is:", gcd(48, 18))

After executing the above code, we get the following output ?

GCD of 48 and 18 is: 6

Finding Length of a String Using Recursion

We can use recursion to find the length of a string without using Python's built-in len() function. The idea is to count one character at a time until the string becomes empty. For example ?

  • Length of "hi" is 2
  • Length of "Python" is 6
  • Length of "" (empty string) is 0

The recursive approach works by removing the first character of the string and counting what is left. We keep doing this until the string becomes empty. Here is the recursive logic ?

  • If the string is empty, return 0: This is the base case. When there are no characters left, we stop and return 0.
  • Otherwise, return 1 + length of the remaining string: This is the recursive case. We count 1 for the current character and call the function again for the rest of the string.

In simpler terms, the function keeps removing one character from the start and adding 1 to the count until nothing is left. Then it adds up all the 1s and gives the total length.

Example

In the example below, we are using recursion to find the length of a string by removing one character at a time and counting how many characters are in total ?

# Recursive function to find length of a string
def string_length(s):
   if s == "":
      # base case
      return 0   
   else:
      # recursive case
      return 1 + string_length(s[1:])   

# Test the function
print("Length of 'Python' is:", string_length("Python"))

The result produced is as shown below ?

Length of 'Python' is: 6

How Does Recursion Work in Memory?

When a recursive function is called in Python, the program uses a special structure called the call stack to keep track of each function call.

What happens when a recursive function runs?

Every time the function calls itself ?

  • A new memory frame (a small block of memory) is created to store the current function's variables and its state.
  • This frame is pushed onto the call stack (imagine stacking books on top of each other; each function call is a new book).

When the base case is reached:

  • No more recursive calls are made.
  • The function starts returning values to the previous function calls one by one.
  • The stack starts to unwind, i.e., each memory frame is removed (or popped) from the stack as its job is done.

What if there is no base case?

  • If the function keeps calling itself forever without stopping, the stack becomes too full. Python will raise a RecursionError and stop the program when the maximum recursion depth is exceeded.

By default, Python allows up to 1000 recursive calls. You can check the limit using ?

import sys
print(sys.getrecursionlimit())

And if needed, you can increase the limit like this ?

import sys

# example: increase to 2000
sys.setrecursionlimit(2000)  
Be careful when increasing the recursion limit; too much recursion can crash the program or slow down your system.
Updated on: 2025-04-11T14:30:18+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements