[英]Exit a specific while loop
Can I break out of a nested while loop? 我可以打破嵌套的while循环吗?
I have highlighted with yellow of what happens in my code. 我用黄色突出显示了代码中发生的事情。 As can be seen, if the condition is true it breaks out and the first 'exit' line is executed.
可以看出,如果条件为真,它将中断并执行第一条“退出”行。
Is there a way I can exit the last exit code (marked with blue ring) 有没有办法我可以退出上一个退出代码(标有蓝圈)
Use a custom exception to break out. 使用自定义例外进行爆发。
class ExitLoop(Exception):
pass
try:
while True:
while other:
raise ExitLoop()
except ExitLoop:
exit()
Instead of breaking in the inner loop, set a flag. 设置中断标志而不是破坏内部循环。 At the outer loop break if flag is set.
如果设置了标志,则在外循环中断。
flag = False
while True:
if flag:
break
while otherCondition:
try:
flag = True
except ValueError:
print('oops')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.