【问题标题】:Try except recursion or while loop?尝试除了递归或while循环?
【发布时间】:2019-03-17 18:21:05
【问题描述】:

我正在上一门 Python 课程,他们建议在 while 循环中使用 try 和 except 块,以便在满足条件之前不断询问输入。直觉上我觉得像这样在“except”块中再次调用函数会更短:

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

exceptiontest()

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

【问题讨论】:

  • 如果您一次又一次地调用该函数,您正在调用堆栈上装订函数调用:exceptiontest(exceptiontest(exceptiontest(exceptiontest(exceptiontest(exceptiontest(exceptiontest())))))):。那是不必要的努力和不好的做法 - while 循环不需要这样做,因为您停留在同一个函数中。
  • 不要让错误悄悄地过去。很好用:除了ValueError as e: print(e)。
  • @Patrick Artner,非常有用的链接,谢谢。我知道它与性能和调用堆栈有关。很好的帮助!

标签: python recursion error-handling while-loop try-except


【解决方案1】:

使用 while 循环的另一个尚未提及的原因是您可以利用 Python 3.8 附带的 assignment expressions

函数add 封装了获取两个数字并尝试将它们相加。

def add():
    'try to add two numbers from user input, return None on failure'
    x = input('number 1: ')
    y = input('number 2: ')
    try:
        return float(x) + float(y)
    except TypeError, ValueError:
        return None

只要没有result,以下while 循环就会运行。

while (result := add()) is None:
    print('you made a mistake, make sure to input two numbers!')

# use result

【讨论】:

    【解决方案2】:

    while 循环,有两个原因

    • 读起来更清楚:如果不成功,再试一次
    • 递归不是免费的。它使先前的函数堆栈保持打开状态。它可能会用完内存(在这种情况下可能不会,但原则上应避免)

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 永远不要低估傻瓜的聪明才智。
      • 这是有道理的。我认为这可能与资源有关,但我并不清楚。感谢您的帮助!
      猜你喜欢
      • 1970-01-01
      • 2013-08-12
      • 1970-01-01
      • 2021-02-15
      • 2016-02-27
      • 2012-08-04
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      相关资源
      最近更新 更多