What is the 'Maximum depth exceeded' error in Python?

A Python program may throw the ‘Maximum depth exceeded’ error because of two things:

  • The system stack limit has been exceeded.
  • There is an infinite loop in the code.

Remember that in recursive codes, system stack is updated for every recursive call.

Consider the example below:

def calc_power(a, exp):
    if exp == 0:
        return 1
    temp = calc_power(a, exp/2)
    temp *= temp
    return a*temp if exp%2 else temp

This code gives a runtime error.

svg viewer

Code

In the above code, there is an infinite recursive call that never reaches the base case (i.e., exp == 0) because the / symbol in Python returns a float value, so, it never returns an exact 0 integer value. Therefore, the solution to this kind of problem​ is to use integer division (//).

def calc_power(a, exp):
if exp == 0:
return 1
temp = calc_power(a, exp/2) # infinite loop
temp *= temp
return a*temp if exp%2 else temp
print (calc_power(5, 2))
Scroll down to see the error.

If there is no infinite loop in the code, try increasing the size of the system stack by importing the sys module:

import sys
sys.setrecursionlimit(10000)

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved