PYnative

Practice Coding

  • Python โ–ผ
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises โ–ผ
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsโ–ผ
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersโ–ผ
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home ยป Python ยป Basics ยป Recursion in Python

Recursion in Python

Updated on:ย December 4, 2026 | Leave a Comment

Recursion is a technique where a function calls itself to solve a problem. Instead of solving a big problem in one go, a recursive function breaks it into a smaller version of the same problem, solves that, and repeats until the problem becomes so small that the answer is obvious.

Recursion is used everywhere in programming: calculating factorials, walking through folders on a disk, searching sorted data, processing nested lists and JSON, and working with trees and graphs. Once you understand it, many problems that look hard with loops become short and elegant.

In this tutorial, you will learn how recursion works in Python, how Python tracks recursive calls with the call stack, the different types of recursion, the recursion limit, how to speed up recursive functions with memoization, and when you should use a loop instead.

Table of contents

  • What is Recursion in Python?
  • A Simple Recursion Example
  • How Recursion Works: The Call Stack
  • Recursion Examples in Python
    • 1. Sum of Natural Numbers
    • 2. Sum of a List
    • 3. Power of a Number
    • 4. Reverse a String
    • 5. Check if a String is a Palindrome
    • 6. Sum of Digits of a Number
    • 7. Fibonacci Series
    • 8. Greatest Common Divisor (GCD)
    • 9. Binary Search
    • 10. Flatten a Nested List
    • 11. Tower of Hanoi
    • 12. Generate All Permutations
    • 13. Walk Through Nested Folders
  • Types of Recursion
    • 1. Direct Recursion
    • 2. Indirect Recursion
    • 3. Tail Recursion
    • 4. Head Recursion
    • 5. Tree Recursion
  • Python Recursion Limit
    • Changing the Recursion Limit
  • Memoization: Speed Up Recursion
    • Memoization Using a Dictionary
    • Memoization Using functools.lru_cache
    • Comparing the Speed
  • Recursion vs Iteration
  • When to Use Recursion
  • Advantages and Disadvantages of Recursion
  • Common Mistakes in Recursion
    • 1. Missing or Unreachable Base Case
    • 2. Forgetting to Return the Recursive Call
    • 3. Not Making the Problem Smaller
    • 4. Recomputing the Same Values
    • 5. Using Recursion for Very Large Inputs
  • Summary

What is Recursion in Python?

A recursive function is a function that calls itself during its execution. Each call works on a smaller or simpler input than the previous one, and the calls stop when the input reaches a simple case that can be answered directly.

A real-life analogy: imagine you are standing in a long queue and want to know your position. You ask the person in front of you, “What is your position?” They ask the person in front of them, and so on. The person at the very front knows they are number 1 (this is the base case). That answer travels back down the line, and each person adds 1 to it until the answer reaches you.

Every recursive function has two essential parts:

  1. Base case: The condition under which the function stops calling itself and returns a value directly. Without a base case, the function would call itself forever.
  2. Recursive case: The part where the function calls itself with a smaller or simpler input, moving step by step toward the base case.

Syntax:

def recursive_function(parameters):
    if base_condition:          # Base case: stop here
        return base_value
    else:                       # Recursive case: call itself with a smaller input
        return recursive_function(smaller_parameters)Code language: Python (python)

A Simple Recursion Example

Letโ€™s start with a function that counts down from a given number to 1.

def countdown(n):
    if n == 0:                  # Base case
        print("Done!")
        return
    print(n)
    countdown(n - 1)            # Recursive case: smaller input

countdown(5)Code language: Python (python)

Output:

5
4
3
2
1
Done!Code language: Python (python)

Here is what happens:

  • countdown(5) prints 5 and calls countdown(4).
  • countdown(4) prints 4 and calls countdown(3), and so on.
  • When n becomes 0, the base case runs, prints Done!, and the function stops calling itself.

Notice that each call passes n - 1. This guarantees that n eventually reaches 0. A recursive function must always make progress toward its base case.

How Recursion Works: The Call Stack

To really understand recursion, you need to know what Python does behind the scenes when a function calls itself.

Each time a function is called, Python creates a stack frame. A frame stores that callโ€™s local variables and the point where execution should continue when it returns. Frames are placed on the call stack, which works like a stack of plates: the most recent call sits on top, and it must finish before the calls below it can continue.

Letโ€™s trace the classic factorial function. The factorial of n (written n!) is the product of all positive integers up to n: 5! = 5 ร— 4 ร— 3 ร— 2 ร— 1 = 120. It can be defined recursively as n! = n ร— (n - 1)!, with 0! = 1 and 1! = 1.

def factorial(n):
    if n <= 1:                     # Base case
        return 1
    return n * factorial(n - 1)   # Recursive case

print(factorial(5))Code language: Python (python)

Output:

120Code language: Python (python)

Recursion happens in two phases:

  1. Winding phase (going down): The function keeps calling itself and frames pile up on the stack until the base case is reached. No multiplication has happened yet; each frame is waiting for the result of the call below it.
  2. Unwinding phase (coming back up): The base case returns 1. Each waiting frame then receives the result, finishes its multiplication, returns, and is removed from the stack.
factorial(5)
= 5 * factorial(4)
= 5 * (4 * factorial(3))
= 5 * (4 * (3 * factorial(2)))
= 5 * (4 * (3 * (2 * factorial(1))))
= 5 * (4 * (3 * (2 * 1)))        <- base case reached, start unwinding
= 5 * (4 * (3 * 2))
= 5 * (4 * 6)
= 5 * 24
= 120Code language: Python (python)

You can watch both phases by adding print statements and an indentation level that shows how deep each call is:

def factorial(n, depth=0):
    indent = "    " * depth
    print(f"{indent}factorial({n}) called")
    if n <= 1:
        print(f"{indent}base case reached, returning 1")
        return 1
    result = n * factorial(n - 1, depth + 1)
    print(f"{indent}factorial({n}) returns {result}")
    return result

factorial(4)Code language: Python (python)

Output:

factorial(4) called
    factorial(3) called
        factorial(2) called
            factorial(1) called
            base case reached, returning 1
        factorial(2) returns 2
    factorial(3) returns 6
factorial(4) returns 24Code language: Python (python)

The calls go deeper (winding) until factorial(1), and then the results come back in reverse order (unwinding). This “last in, first out” behavior is exactly how a stack works.


Recursion Examples in Python

The best way to get comfortable with recursion is to practice on small problems. For each example, look for the base case and ask how the input gets smaller on every call.

1. Sum of Natural Numbers

The sum of the first n natural numbers is n plus the sum of the first n - 1 numbers.

def sum_natural(n):
    if n == 0:                       # Base case
        return 0
    return n + sum_natural(n - 1)    # Recursive case

print(sum_natural(10))Code language: Python (python)

Output:

55Code language: Python (python)

2. Sum of a List

The sum of a list is the first element plus the sum of the rest of the list. An empty list has a sum of 0.

def list_sum(numbers):
    if not numbers:                          # Base case: empty list
        return 0
    return numbers[0] + list_sum(numbers[1:])

print(list_sum([4, 8, 15, 16, 23, 42]))Code language: Python (python)

Output:

108Code language: Python (python)

Note: numbers[1:] creates a new list on every call, which costs extra time and memory. For large lists, pass an index instead of slicing:

def list_sum(numbers, index=0):
    if index == len(numbers):                # Base case: past the last element
        return 0
    return numbers[index] + list_sum(numbers, index + 1)

print(list_sum([4, 8, 15, 16, 23, 42]))Code language: Python (python)

Output:

108Code language: Python (python)

3. Power of a Number

baseexp equals base ร— baseexp - 1, and any number raised to the power 0 is 1.

def power(base, exp):
    if exp == 0:                         # Base case
        return 1
    return base * power(base, exp - 1)

print(power(2, 10))
print(power(5, 3))Code language: Python (python)

Output:

1024
125Code language: Python (python)

This makes exp recursive calls. A smarter version, called fast exponentiation, halves the exponent on each call, so it needs only about log2(exp) calls:

def fast_power(base, exp):
    if exp == 0:
        return 1
    half = fast_power(base, exp // 2)
    if exp % 2 == 0:
        return half * half
    return base * half * half

print(fast_power(2, 10))
print(fast_power(3, 13))Code language: Python (python)

Output:

1024
1594323Code language: Python (python)

4. Reverse a String

Take the last character and attach it to the front of the reversed remaining string.

def reverse_string(text):
    if len(text) <= 1:                       # Base case
        return text
    return text[-1] + reverse_string(text[:-1])

print(reverse_string("PYnative"))Code language: Python (python)

Output:

evitanYPCode language: Python (python)

5. Check if a String is a Palindrome

A palindrome reads the same forwards and backwards. Compare the first and last characters, then check the inner part of the string.

def is_palindrome(text):
    if len(text) <= 1:                 # Base case: empty or single character
        return True
    if text[0] != text[-1]:            # Base case: mismatch found
        return False
    return is_palindrome(text[1:-1])   # Check the inner string

print(is_palindrome("level"))
print(is_palindrome("racecar"))
print(is_palindrome("python"))Code language: Python (python)

Output:

True
True
FalseCode language: Python (python)

This function has two base cases. A recursive function can have as many base cases as the problem needs.

6. Sum of Digits of a Number

n % 10 gives the last digit, and n // 10 removes it.

def sum_of_digits(n):
    if n < 10:                              # Base case: single digit
        return n
    return n % 10 + sum_of_digits(n // 10)

print(sum_of_digits(98765))Code language: Python (python)

Output:

35Code language: Python (python)

7. Fibonacci Series

In the Fibonacci series, each number is the sum of the two numbers before it: 0, 1, 1, 2, 3, 5, 8, 13, and so on.

def fibonacci(n):
    if n <= 1:                                   # Base cases: fib(0)=0, fib(1)=1
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)   # Two recursive calls

for i in range(10):
    print(fibonacci(i), end=" ")Code language: Python (python)

Output:

0 1 1 2 3 5 8 13 21 34 Code language: Python (python)

This version is easy to read but very slow for large n, because it calculates the same values again and again. You will learn how to fix this in the memoization section.

8. Greatest Common Divisor (GCD)

Euclidโ€™s algorithm is naturally recursive: the GCD of a and b is the same as the GCD of b and a % b. When b becomes 0, the answer is a.

def gcd(a, b):
    if b == 0:                 # Base case
        return a
    return gcd(b, a % b)

print(gcd(48, 18))
print(gcd(270, 192))Code language: Python (python)

Output:

6
6Code language: Python (python)

9. Binary Search

Binary search finds an item in a sorted list by checking the middle element and then searching only the left or right half. Each call cuts the search range in half.

def binary_search(items, target, low, high):
    if low > high:                     # Base case: range is empty, not found
        return -1

    mid = (low + high) // 2
    if items[mid] == target:           # Base case: found
        return mid
    elif target < items[mid]:
        return binary_search(items, target, low, mid - 1)    # Search left half
    else:
        return binary_search(items, target, mid + 1, high)   # Search right half

numbers = [3, 9, 14, 21, 35, 47, 58, 62, 79, 91]
print(binary_search(numbers, 47, 0, len(numbers) - 1))
print(binary_search(numbers, 50, 0, len(numbers) - 1))Code language: Python (python)

Output:

5
-1Code language: Python (python)

10. Flatten a Nested List

Recursion is ideal for data whose depth is unknown in advance. A nested list can contain lists inside lists to any level, so a loop alone cannot handle it easily.

def flatten(nested):
    result = []
    for item in nested:
        if isinstance(item, list):
            result.extend(flatten(item))   # Recursive case: item is a list
        else:
            result.append(item)            # Base case: item is a plain value
    return result

data = [1, [2, 3], [4, [5, 6, [7, 8]]], 9]
print(flatten(data))Code language: Python (python)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]Code language: Python (python)

11. Tower of Hanoi

In the Tower of Hanoi puzzle, you move a stack of disks from one rod to another, using a third rod as a helper. You can move only one disk at a time, and a larger disk can never be placed on a smaller one.

The recursive solution is surprisingly short: move the top n - 1 disks out of the way, move the largest disk, then move the n - 1 disks on top of it.

def hanoi(n, source, target, helper):
    if n == 1:
        print(f"Move disk 1 from {source} to {target}")
        return
    hanoi(n - 1, source, helper, target)    # Move n-1 disks out of the way
    print(f"Move disk {n} from {source} to {target}")
    hanoi(n - 1, helper, target, source)    # Move n-1 disks onto the largest disk

hanoi(3, "A", "C", "B")Code language: Python (python)

Output:

Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to CCode language: Python (python)

Solving n disks always takes 2n - 1 moves, so 3 disks take 7 moves.

12. Generate All Permutations

To list every arrangement of a string, fix each character in the first position and recursively arrange the remaining characters.

def permutations(text):
    if len(text) <= 1:                      # Base case
        return [text]
    result = []
    for i, char in enumerate(text):
        remaining = text[:i] + text[i + 1:]
        for perm in permutations(remaining):
            result.append(char + perm)
    return result

print(permutations("abc"))Code language: Python (python)

Output:

['abc', 'acb', 'bac', 'bca', 'cab', 'cba']Code language: Python (python)

In real projects, use itertools.permutations(), but writing it yourself is a great recursion exercise.

13. Walk Through Nested Folders

File systems are trees: a folder can contain files and other folders. The function below prints a folder tree by calling itself for every subfolder it finds.

import os

def print_tree(path, level=0):
    for name in sorted(os.listdir(path)):
        full_path = os.path.join(path, name)
        print("    " * level + name)
        if os.path.isdir(full_path):
            print_tree(full_path, level + 1)   # Recursive call for subfolder

print_tree(".")Code language: Python (python)

There is no explicit if base case here. The recursion stops naturally when a folder has no subfolders, because the loop simply ends without making another call.


Types of Recursion

Recursive functions are commonly grouped by how and where they call themselves.

1. Direct Recursion

A function calls itself directly. All the examples above, such as factorial() and countdown(), use direct recursion.

2. Indirect Recursion

Function A calls function B, and function B calls function A. This is also called mutual recursion.

def is_even(n):
    if n == 0:
        return True
    return is_odd(n - 1)

def is_odd(n):
    if n == 0:
        return False
    return is_even(n - 1)

print(is_even(10))
print(is_odd(7))
print(is_even(3))Code language: Python (python)

Output:

True
True
FalseCode language: Python (python)

3. Tail Recursion

In tail recursion, the recursive call is the very last operation in the function; nothing is left to do after it returns. The running result is usually passed along in an extra parameter called an accumulator.

def factorial_tail(n, accumulator=1):
    if n <= 1:
        return accumulator
    return factorial_tail(n - 1, n * accumulator)   # Last operation is the call

print(factorial_tail(5))Code language: Python (python)

Output:

120Code language: Python (python)

Compare it with the regular factorial(), where n * factorial(n - 1) still has to multiply after the call returns, so that version is not tail recursive.

Important: Some languages optimize tail calls so they donโ€™t grow the stack. Python does not perform tail call optimization. A tail-recursive Python function still uses one stack frame per call and is still limited by the recursion limit. The benefit of writing it this way is that it is very easy to convert into a loop.

4. Head Recursion

In head recursion, the recursive call happens first, and the function does its own work after the call returns. Compare these two functions:

def print_head(n):
    if n == 0:
        return
    print_head(n - 1)     # Recursive call first
    print(n, end=" ")     # Work done while unwinding

def print_tail(n):
    if n == 0:
        return
    print(n, end=" ")     # Work done first
    print_tail(n - 1)     # Recursive call last

print_head(5)
print()
print_tail(5)Code language: Python (python)

Output:

1 2 3 4 5 
5 4 3 2 1 Code language: Python (python)

Both functions have the same structure, but moving the print() before or after the recursive call reverses the order of the output.

5. Tree Recursion

A function makes more than one recursive call each time it runs. The calls branch out like a tree. The fibonacci() function and the Tower of Hanoi are examples of tree recursion.

                    fib(5)
                 /          \
            fib(4)          fib(3)
           /      \         /     \
       fib(3)    fib(2)  fib(2)   fib(1)
       /    \     /   \   /   \
   fib(2) fib(1) ...   ...  ...Code language: Python (python)

Notice that fib(3) and fib(2) are calculated several times. The number of calls grows exponentially, roughly O(2n). Memoization solves this problem.


Python Recursion Limit

Because every call adds a frame to the call stack, a function that recurses too deeply could use up all the memory reserved for the stack and crash the program. To prevent this, Python sets a maximum recursion depth. By default, it is 1000.

You can check it with sys.getrecursionlimit():

import sys

print(sys.getrecursionlimit())Code language: Python (python)

Output:

1000Code language: Python (python)

If a function goes deeper than this limit, Python raises a RecursionError:

def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

try:
    factorial(5000)
except RecursionError as e:
    print("RecursionError:", e)Code language: Python (python)

Output:

RecursionError: maximum recursion depth exceededCode language: Python (python)

The same error appears if you forget the base case, because the function never stops calling itself:

def no_base_case(n):
    return no_base_case(n - 1)   # No base case: infinite recursion

no_base_case(5)Code language: Python (python)

Output:

Traceback (most recent call last):
  ...
  File "main.py", line 2, in no_base_case
    return no_base_case(n - 1)   # No base case: infinite recursion
           ~~~~~~~~~~~~^^^^^^^
RecursionError: maximum recursion depth exceededCode language: Python (python)

Changing the Recursion Limit

You can raise the limit with sys.setrecursionlimit():

import sys

sys.setrecursionlimit(10000)

def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

result = factorial(3000)
print("factorial(3000) computed successfully")
print("It has", result.bit_length(), "bits")Code language: Python (python)

Output:

factorial(3000) computed successfully
It has 30332 bitsCode language: Python (python)

Use this carefully. The recursion limit is a safety net. Setting it too high can make Python crash with a segmentation fault instead of a clean RecursionError, because the real operating system stack runs out. If you need very deep recursion, it is usually better to rewrite the function with a loop.


Memoization: Speed Up Recursion

Memoization means storing the result of a function call and reusing it the next time the same input appears, instead of calculating it again. It is the standard fix for slow tree-recursive functions such as Fibonacci.

First, letโ€™s count how many calls the plain Fibonacci function makes:

call_count = 0

def fibonacci(n):
    global call_count
    call_count += 1
    if n <= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(25))
print("Function calls:", call_count)Code language: Python (python)

Output:

75025
Function calls: 242785Code language: Python (python)

Nearly a quarter of a million calls to compute a single number. Now letโ€™s cache the results.

Memoization Using a Dictionary

def fibonacci(n, memo={}):
    if n in memo:                 # Return the cached result
        return memo[n]
    if n <= 1:
        return n
    memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo)
    return memo[n]

print(fibonacci(25))
print(fibonacci(100))Code language: Python (python)

Output:

75025
354224848179261915075Code language: Python (python)

Each value is calculated only once, so the function now makes about n calls instead of roughly 2n.

Note: This example uses a mutable default argument (memo={}) on purpose so the cache is shared between calls. In most other functions, a mutable default argument is a bug, so use this pattern only when you really want a shared cache.

Memoization Using functools.lru_cache

Python has memoization built in. Add the @lru_cache decorator from the functools module, and Python caches the results for you:

from functools import lru_cache

@lru_cache(maxsize=None)
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(100))
print(fibonacci.cache_info())Code language: Python (python)

Output:

354224848179261915075
CacheInfo(hits=98, misses=101, maxsize=None, currsize=101)Code language: Python (python)

In Python 3.9 and later, you can also use @functools.cache, which is a shorter way of writing @lru_cache(maxsize=None). Keep in mind that the arguments of a cached function must be hashable, so you cannot pass a list directly.

Comparing the Speed

import time
from functools import lru_cache

def fib_plain(n):
    if n <= 1:
        return n
    return fib_plain(n - 1) + fib_plain(n - 2)

@lru_cache(maxsize=None)
def fib_cached(n):
    if n <= 1:
        return n
    return fib_cached(n - 1) + fib_cached(n - 2)

start = time.perf_counter()
fib_plain(30)
print(f"Without memoization: {time.perf_counter() - start:.4f} seconds")

start = time.perf_counter()
fib_cached(30)
print(f"With memoization:    {time.perf_counter() - start:.6f} seconds")Code language: Python (python)

Output:

Without memoization: 0.0893 seconds
With memoization:    0.000018 secondsCode language: Python (python)

The exact times depend on your machine, but the memoized version is thousands of times faster, and the gap grows quickly as n increases.


Recursion vs Iteration

Any recursive function can be rewritten using a loop (iteration), and vice versa. Here is factorial written both ways:

def factorial_recursive(n):
    if n <= 1:
        return 1
    return n * factorial_recursive(n - 1)

def factorial_iterative(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

print(factorial_recursive(6))
print(factorial_iterative(6))Code language: Python (python)

Output:

720
720Code language: Python (python)

Both return the same result, but they behave differently:

AspectRecursionIteration
How it repeatsFunction calls itselfLoop (for / while)
Stop conditionBase caseLoop condition becomes false
Memory useOne stack frame per callConstant (no extra frames)
Speed in PythonSlower, function calls have overheadUsually faster
Depth limitLimited by the recursion limit (1000 by default)No such limit
ReadabilityVery clear for trees, nested data, divide and conquerClearer for simple, linear repetition
RiskRecursionError if the base case is wrongInfinite loop if the condition is wrong

Converting a tail-recursive function to a loop: Because Python does not optimize tail calls, a common technique is to turn the accumulator into a variable and the recursive call into a loop step:

# Tail-recursive version
def gcd_recursive(a, b):
    if b == 0:
        return a
    return gcd_recursive(b, a % b)

# Same logic as a loop
def gcd_iterative(a, b):
    while b != 0:
        a, b = b, a % b
    return a

print(gcd_recursive(1071, 462))
print(gcd_iterative(1071, 462))Code language: Python (python)

Output:

21
21Code language: Python (python)

When to Use Recursion

Recursion is a good choice when:

  • The problem is naturally defined in terms of smaller versions of itself, such as factorial, GCD, or Fibonacci.
  • You are working with hierarchical or nested data: trees, folder structures, nested lists, JSON, or HTML.
  • You are using divide and conquer algorithms such as binary search, merge sort, and quick sort.
  • You need backtracking, such as generating permutations and combinations, or solving mazes and Sudoku.
  • The recursion depth stays small (well under the recursion limit).

Prefer a loop when:

  • The task is a simple, linear repetition, like summing a list or counting.
  • The input can be very large, so the recursion would go thousands of levels deep.
  • Performance and memory usage are critical.

Advantages and Disadvantages of Recursion

Advantages

  • Code is often shorter, cleaner, and closer to the mathematical definition of the problem.
  • It handles nested and tree-like structures naturally, without managing your own stack.
  • Complex problems like Tower of Hanoi and permutations become much easier to express.

Disadvantages

  • Each call uses stack memory, so deep recursion uses more memory than a loop.
  • Function calls in Python are relatively expensive, so recursion is usually slower.
  • Python limits recursion depth and does not optimize tail calls.
  • Recursive code can be harder to trace and debug for beginners.

Common Mistakes in Recursion

1. Missing or Unreachable Base Case

If the input never reaches the base case, the function recurses until it hits a RecursionError. In the example below, n skips over 0 when you start with an odd number:

def countdown_by_two(n):
    if n == 0:              # Never true when n starts as an odd number
        return
    print(n, end=" ")
    countdown_by_two(n - 2)

# countdown_by_two(5)   # 5, 3, 1, -1, -3, ... RecursionErrorCode language: Python (python)

Fix: Use a condition that catches every possible ending, such as if n <= 0:.

2. Forgetting to Return the Recursive Call

A very common bug is calling the function recursively but forgetting to return its result. The result is lost, and the function returns None.

def gcd(a, b):
    if b == 0:
        return a
    gcd(b, a % b)      # Bug: result is not returned

print(gcd(48, 18))Code language: Python (python)

Output:

NoneCode language: Python (python)

The base case does return 6, but only to the call one level above it, which then throws that value away. The outermost call reaches the end of the function and returns None. If the lost value is used in a calculation, such as n + func(n - 1), you will instead get a TypeError because Python cannot add a number and None.

Fix: Always write return gcd(b, a % b).

3. Not Making the Problem Smaller

Every recursive call must move closer to the base case. Calling factorial(n) instead of factorial(n - 1), or list_sum(numbers) instead of list_sum(numbers[1:]), causes infinite recursion.

4. Recomputing the Same Values

Tree recursion like the plain fibonacci() function repeats a huge amount of work. If your recursive function is slow and calls itself with the same arguments many times, add @lru_cache.

5. Using Recursion for Very Large Inputs

A recursive function that works for n = 100 may fail for n = 10000. If the depth depends directly on the input size, consider a loop or an explicit stack (a list you push to and pop from) instead.

Summary

  • A recursive function is a function that calls itself to solve smaller versions of the same problem.
  • Every recursive function needs a base case that stops the recursion and a recursive case that moves toward it.
  • Python uses the call stack to track each call. Calls pile up while winding and are resolved in reverse order while unwinding.
  • Common types are direct, indirect, tail, head, and tree recursion.
  • Pythonโ€™s default recursion limit is 1000. Exceeding it raises RecursionError. Python does not optimize tail calls.
  • Use memoization (@lru_cache or a dictionary) to avoid repeating work in tree-recursive functions.
  • Use recursion for trees, nested data, divide and conquer, and backtracking. Use loops for simple repetition and very large inputs.

Recursion takes some practice before it feels natural. Start by tracing small examples on paper, always identify the base case first, and then check that every call makes the problem smaller. To keep practicing, try the Python Functions Exercises and test yourself with the Python Functions Quiz.

Filed Under: Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Iโ€™m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com