如何跳出多个循环?

2024-04-20 03:37:54 发布

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

给定以下代码(不起作用):

while True:
    #snip: print out current state
    while True:
        ok = get_input("Is this ok? (y/n)")
        if ok.lower() == "y": break 2 #this doesn't work :(
        if ok.lower() == "n": break
    #do more processing with menus and stuff

有办法让这一切顺利吗?或者,如果用户满意的话,我是否需要先执行一个检查以跳出输入循环,然后执行另一个更为有限的检查以同时执行外部循环?


Tags: 代码trueinputgetifokcurrentout
3条回答

这是另一个简短的方法。缺点是你只能打破外循环,但有时这正是你想要的。

for a in xrange(10):
    for b in xrange(20):
        if something(a, b):
            # Break the inner loop...
            break
    else:
        # Continue if the inner loop wasn't broken.
        continue
    # Inner loop was broken, break the outer.
    break

这使用了在:Why does python use 'else' after for and while loops?中解释的for/else构造

关键洞察:似乎只有似乎外环总是断裂。但是如果内部循环没有中断,外部循环也不会中断。

continue语句是这里的魔力。在for else子句中。By definition如果没有内部中断,就会发生这种情况。在这种情况下,continue巧妙地避开了外部的断裂。

PEP 3136建议标记为break/continue。Guido rejected it因为“需要此功能的复杂代码非常罕见”。不过,PEP确实提到了一些解决方法(例如异常技术),而Guido认为在大多数情况下,使用return进行重构会更简单。

我的第一个直觉是将嵌套循环重构为一个函数,并使用return来中断。

相关问题 更多 >