Python双功能递归

发布于 2025-02-01 15:34:59 字数 923 浏览 7 评论 0原文

我正在研究VS代码的Pygame项目,并意外地编​​写了以下代码:

def appear():
    end()

def end():
    appear()

我的Pylance没有任何错误。 我想知道为什么在第2行中没有显示 “ 未定义”。

而且,当我在单独的python文件中运行这片小件代码时:

def appear():
    end()

def end():
    appear()

appear()

解释器也没有显示名称eRror,而是在四到五秒钟后显示出一个recursionError,类似的是:

...
  File "c:/Users/.../test.py", line 5, in end
    appear()
  File "c:/Users/.../test.py", line 2, in appear
    end()
  File "c:/Users/.../test.py", line 5, in end
    appear()
  File "c:/Users/.../test.py", line 2, in appear
    end()
  File "c:/Users/.../test.py", line 5, in end
    appear()
  File "c:/Users/.../test.py", line 2, in appear
    end()
  File "c:/Users/.../test.py", line 5, in end
    appear()
  File "c:/Users/.../test.py", line 2, in appear
    end()
RecursionError: maximum recursion depth exceeded

这是什么意思?

I was working on a pygame project on VS code and accidentally written the following code:

def appear():
    end()

def end():
    appear()

and my pylance shown no error.
I was wondering why in line 2 it was not showing
"end is not defined".

And when I ran this small piece of code in a seperate python file:

def appear():
    end()

def end():
    appear()

appear()

the interpreter too did not show NameError but instead after four to five seconds it shows a RecursionError, something like this:

...
  File "c:/Users/.../test.py", line 5, in end
    appear()
  File "c:/Users/.../test.py", line 2, in appear
    end()
  File "c:/Users/.../test.py", line 5, in end
    appear()
  File "c:/Users/.../test.py", line 2, in appear
    end()
  File "c:/Users/.../test.py", line 5, in end
    appear()
  File "c:/Users/.../test.py", line 2, in appear
    end()
  File "c:/Users/.../test.py", line 5, in end
    appear()
  File "c:/Users/.../test.py", line 2, in appear
    end()
RecursionError: maximum recursion depth exceeded

What does it mean??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

杀お生予夺 2025-02-08 15:34:59

在Python中,必须在调用函数之前定义功能(执行,而不仅仅是在另一个定义中使用)。因此,您的功能定义没有问题。好吧,除了创建无限的递归循环外... python解释器提供的错误(“ recursionError:最大递归深度超过”)时,由于执行的事实是因为python只允许一定水平的递归,我猜这是如果我没记错的话,默认情况下为1000(可以更改)。当您的功能无限期地互相调用时,所有可能的递归已经在这4秒内完成。

In Python, functions must be defined before they are called (executed, not just used in another definition). Therefore, there is no problem with your function definitions. Well, apart from creating an infinite recursion loop... The error the Python interpreter provided ("RecursionError: maximum recursion depth exceeded") when you executed it happens due to the fact that Python allows only certain level of recursion, which I guess is 1000 by default (can be changed) if I remember correctly. As your functions call each other indefinitely, all the possible recursions have been done in those 4 seconds.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文