如何从try-catch块内部中断for循环?

2024-09-28 05:28:38 发布

您现在位置:Python中文网/ 问答频道 /正文

如果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,则用于引发实际异常


Tags: 方法代码inforifpassraisetry
2条回答

我相信最干净的方法是在continue块内部except,然后break在它之后执行。在这种情况下,您甚至不必使用avar(除非我误解了这个问题)。你知道吗

attempts = ['I15', 'J15']
for attempt in attempts:
    try:
        afunc(attempt)
    except KeyError:
        continue
    break

如果您确实需要avar供以后使用:

attempts = ['I15', 'J15']
for attempt in attempts:
    try:
        avar = afunc(attempt)
    except KeyError:
        continue
    break
print(avar) # avar is a available here, as long as at least one attempt was successful

您需要for … else概念:https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

attempts = ['I15', 'J15']
for attempt in attempts:
    try:
        avar = afunc(attempt)
    except KeyError:
        # error, let's try another item from attempts
        continue
    else:
        # success, let's get out of the loop
        break
else:
    # this happens at the end of the loop if there is no break
    raise KeyError

相关问题 更多 >

    热门问题