【发布时间】:2021-12-31 17:16:24
【问题描述】:
所以我有一个简单的这个函数,它在出错时会被自己再次调用,直到它返回没有错误。
def enter_r_h() -> (float, float):
try:
r = float(input("\n--> Enter the radius of the cylinder\n"))
h = float(input("--> Enter the height of the cylinder\n"))
except ValueError:
print("--> Values aren't entered correctly\n")
return enter_r_h()
return r, h
当用户输入错误的值时,这是一个写得很糟糕的解决方法吗,因为理论上这可能会导致堆栈溢出(python 中有这样的事情吗?)或 RecursionError。
【问题讨论】:
-
在实现“尾递归”的语言中,这种事情变成了简单的“跳转”,并且造成的开销很小。 Python 没有,所以这是不好的做法。递归应该保留给需要递归的算法。在这种情况下,迭代解决方案更智能。
-
好的,谢谢您的意见。我不会在实际工作中使用这些聪明的变通方法。
标签: python function recursion exception