“如果循环不中断,则运行代码”的方法是什么?

The*_*ing 2 python loops

我正在尝试编写一个 for 循环来遍历值,如果在循环结束时它没有中断,我希望它运行一些代码。例如:

for i in range(10):
    if someCondition:
        break
#If the loop did NOT break, then...
doSomething()
Run Code Online (Sandbox Code Playgroud)

有一个迂回的方法。例如,

didNotBreak = True
for i in range(10)
    if someCondition:
        didNotbreak = False
        break
if didNotBreak:
    doSomething()
Run Code Online (Sandbox Code Playgroud)

有没有更简单的方法?

khe*_*ood 5

else您可以在循环中使用子句。

\n
for i in range(10):\n    if someCondition:\n        break\nelse:\n    #If the loop did NOT break, then...\n    doSomething()\n
Run Code Online (Sandbox Code Playgroud)\n

else如果循环完成但未命中 则执行该子句break。

\n

请参阅https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops指定:

\n
\n

...当没有发生中断时,循环\xe2\x80\x99s else子句运行

\n
\n