尝试 except 递归或 while 循环?

Dut*_*e91 4 python error-handling recursion while-loop try-except

我正在做一个 python 课程,他们建议在 while 循环中使用 try 和 except 块,以便不断请求输入,直到满足条件。直觉上我觉得在“ except”块中再次调用该函数会更短,如下所示:

def exceptiontest():
    try:
        print(int(input("number 1: "))+int(input("number 2:")))
    except:
        print("a mistake happened")
        exceptiontest()

exceptiontest()
Run Code Online (Sandbox Code Playgroud)

当我在论坛上询问课程时,我得到的答复是不一样。我现在有点困惑。有谁可以帮我澄清一下吗?提前致谢!

Moo*_*awr 5

如果您继续输入错误的输入,则调用中的函数except最终会引发错误。RecursionError: maximum recursion depth exceeded通常,人们在放弃之前不会输入那么多错误数据来引发错误,但是您不必要地将函数调用放在堆栈上。

循环while更好,因为它是一个函数调用,等待有效的输入。IT 不会浪费比其需要更多的资源。

  • 永远不要低估傻瓜的聪明才智。 (2认同)