How to fix recursion error in python

Recursive functions, without limits, could call themselves indefinitely. If you write a recursive function that executes over a certain number of iterations, you’ll encounter the “maximum recursion depth exceeded in comparison” Python error.

This guide discusses what this error means and why it is important. We’ll walk through an example of this error so you can learn how to fix it in your program.

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest
First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

maximum recursion depth exceeded in comparison

Recursive functions are functions that call themselves to find a solution to a program.

Well-written recursive functions include limits to ensure they do not execute infinitely. This may mean that a function should only run until a particular condition is met.

If you write a recursive function that executes more than a particular number of iterations [usually 997], you’ll see an error when you get to the next iteration.

This is because Python limits the depth of a recursion algorithm. This refers to how many times the function can call itself.

You can view the recursion limit in your Python shell using this code:

import sys
print[sys.getrecursionlimit[]]

An Example Scenario

Let’s write a recursive function that calculates a number in the Fibonacci Sequence. In the Fibonacci Sequence, the next number in the sequence is the sum of the last two numbers. The first two numbers in the sequence are 0 and 1.

Here is a recursive function that calculates the Fibonacci Sequence:

def fibonacci[n]:
	if n 

Chủ Đề