codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🐍

Python Programming

29 / 68 topics
24Python Functions25Function Arguments (*args, **kwargs)26Python Lambda Functions27Python Namespace & Scope (Global/Local)28Python Closures29Python Recursion
Tutorials/Python Programming/Python Recursion
🐍Python Programming

Python Recursion

Updated 2026-05-15
30 min read

Python Recursion

Recursion is a fundamental concept in computer science where a function calls itself to solve smaller instances of the same problem. This technique is particularly useful for problems that can be broken down into simpler, repetitive tasks. In this tutorial, we'll explore how to implement recursive functions in Python, understand base cases and recursive cases, and look at practical examples like calculating factorials and Fibonacci numbers.

Introduction

Recursion allows a function to call itself repeatedly until it reaches a base case, which is a condition that stops the recursion. This approach is elegant and often leads to more readable code compared to iterative solutions. However, it's important to handle recursion carefully to avoid infinite loops and understand the limits of recursion depth in Python.

Core Content

Understanding Recursion

Recursion involves two main components:

  1. Base Case: The condition under which the recursion stops. Without a base case, the function would call itself indefinitely, leading to a stack overflow error.
  2. Recursive Case: The part of the function where it calls itself with a modified argument, moving towards the base case.

Factorial Example

Let's start with a classic example: calculating the factorial of a number using recursion.

factorial.py
1def factorial(n):
2 # Base case
3 if n == 0:
4 return 1
5 # Recursive case
6 else:
7 return n * factorial(n - 1)
8
9# Example usage
10result = factorial(5)
11print(result) # Output: 120
Output
120

In this example, the factorial function calls itself with a decremented value of n until it reaches the base case where n is 0. The recursive calls are then resolved from the innermost call to the outermost.

Fibonacci Example

Another common problem solved using recursion is calculating Fibonacci numbers.

fibonacci.py
1def fibonacci(n):
2 # Base cases
3 if n == 0:
4 return 0
5 elif n == 1:
6 return 1
7 # Recursive case
8 else:
9 return fibonacci(n - 1) + fibonacci(n - 2)
10
11# Example usage
12result = fibonacci(7)
13print(result) # Output: 13
Output
13

Here, the fibonacci function calls itself twice in the recursive case to calculate the sum of the two preceding Fibonacci numbers until it reaches the base cases where n is 0 or 1.

Recursion Depth Limit

Python has a recursion limit to prevent infinite recursion and stack overflow errors. The default limit can be checked using the sys.getrecursionlimit() function, and it can be modified using sys.setrecursionlimit(limit).

recursion_limit.py
1import sys
2
3# Check current recursion limit
4print(f"Current recursion limit: {sys.getrecursionlimit()}")
5
6# Set a new recursion limit (be cautious with this)
7sys.setrecursionlimit(3000)
8
9# Example of a deep recursive function
10def deep_recursion(n):
11 if n > 0:
12 deep_recursion(n - 1)
13 else:
14 print("Reached the base case!")
15
16# Call with a high number to test the limit
17deep_recursion(2500)
Output
Current recursion limit: 1000
Reached the base case!

Increasing the recursion limit should be done with caution, as it can lead to crashes if not managed properly.

Practical Example

Let's create a practical example that uses recursion to calculate the greatest common divisor (GCD) of two numbers using the Euclidean algorithm.

gcd.py
1def gcd(a, b):
2 # Base case
3 if b == 0:
4 return a
5 # Recursive case
6 else:
7 return gcd(b, a % b)
8
9# Example usage
10result = gcd(48, 18)
11print(result) # Output: 6
Output
6

In this example, the gcd function calls itself with the remainder of a divided by b until b becomes zero. The last non-zero remainder is the GCD of the two numbers.

Summary

ConceptDescription
Base CaseThe condition that stops recursion.
Recursive CaseThe part of the function where it calls itself with a modified argument.
Recursion Depth LimitThe maximum depth to which a recursive function can call itself.
  • Recursion is a powerful technique for solving problems by breaking them down into smaller, repetitive tasks.
  • Always define a clear base case to prevent infinite recursion.
  • Be aware of the recursion depth limit and handle it appropriately.

What's Next?

Now that you have a solid understanding of recursion in Python, you're ready to explore object-oriented programming concepts. In the next tutorial, we'll dive into classes, objects, inheritance, and polymorphism, which are essential for building complex software systems. Stay tuned!


PreviousPython ClosuresNext Python OOP Concepts

Recommended Gear

Python ClosuresPython OOP Concepts