如何以Python方式重写这段代码?
tried = 0
while tried < 3:
try:
function()
break
except Exception as e:
print e
tried += 1
有我可以使用的内置函数吗?
最佳答案
执行 N 次操作的更 Python 方式是使用 xrange
和 _
变量:
for _ in xrange(3):
try:
function()
break
except Exception as e:
print e
此外,请考虑捕获更具体的异常,而不是根 Exception
类。
关于python - 如何限制调用函数失败的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34666184/