如果try-except块(for循环内)中的代码块成功执行,并且没有调用异常,那么我试图找到一种方法来摆脱这个for循环。你知道吗
以下代码对我不起作用:
attempts = ['I15', 'J15']
for attempt in attempts:
try:
avar = afunc(attempt)
break
except KeyError:
pass
if attempt == attempts[-1]:
raise KeyError
因为在I15
成功执行之后,它仍在调用尝试列表中的J15
项
这里的代码是:
except KeyError:
pass
if attempt == attempts[-1]:
raise KeyError
如果代码已经在attempts
中尝试了整个attempt
,则用于引发实际异常
我相信最干净的方法是在
continue
块内部except
,然后break
在它之后执行。在这种情况下,您甚至不必使用avar
(除非我误解了这个问题)。你知道吗如果您确实需要
avar
供以后使用:您需要
for … else
概念:https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops相关问题 更多 >
编程相关推荐