修复 Python recursionerror: maximum recursion depth exceeded in comparison

Haider Ali 2022年5月17日
修复 Python recursionerror: maximum recursion depth exceeded in comparison

本文将介绍如何解决 Python 中的 recursionerror: maximum recursion depth exceeded in comparison 错误。首先,我们需要了解编程语言中的递归是什么。

修复 Python 中的 recursionerror:比较中超出最大递归深度 错误

当你在函数体内调用函数本身时,就会发生递归。它像一个循环一样工作,直到满足某个条件;递归继续。但在 Python 中情况有所不同。Python 中存在最大递归深度限制。例如,看看下面的代码示例。

#function definition
def func():
    print("Hello Python")
    
    #recursive Call
    func()

#uncomment this to run the function 
#func()

如果你运行上面的代码,它会打印 Hello Python 直到某个限制;然后,它会给出这个确切的错误。那么,如何根据自己的选择调整限制呢?你可以导入模块并检查最大递归深度。看看下面的代码。

#import module
import sys
#function to check the default maximum recursion depth
print(sys.getrecursionlimit())

通过运行上述代码,你将获得系统的递归限制。你可以使用上面的代码检查最大递归深度。要调整限制,你可以运行以下代码。

#To increase or decrease the limit
sys.setrecursionlimit(2000)
Author: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

相关文章 - Python Error