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

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

有办法解决这个问题吗?还是我必须先检查一次,跳出输入循环,然后再检查一次,如果用户满意,再跳出外部循环?


当前回答

如果两个条件为真,则继续循环。

我认为这是一种更python化的方式:

dejaVu = True

while dejaVu:
    while True:
        ok = raw_input("Is this ok? (y/n)")
        if ok == "y" or ok == "Y" or ok == "n" or ok == "N":
            dejaVu = False
            break

其他回答

要跳出多个嵌套循环,而不需要重构为函数,可以使用带有内置StopIteration异常的“模拟goto语句”:

try:
    for outer in range(100):
        for inner in range(100):
            if break_early():
                raise StopIteration

except StopIteration: pass

请参阅使用goto语句打破嵌套循环的讨论。

# this version breaks up to a certain label

break_label = None
while True:
    # snip: print out current state
    while True:
        ok = get_input("Is this ok? (y/n)")
        if ok == "y" or ok == "Y":
            break_label = "outer"   # specify label to break to
            break
        if ok == "n" or ok == "N":
            break
    if break_label:
        if break_label != "inner":
            break                   # propagate up
        break_label = None          # we have arrived!
if break_label:
    if break_label != "outer":
        break                       # propagate up
    break_label = None              # we have arrived!

#do more processing with menus and stuff

我最近遇到了这个问题,为了避免重复的return语句,因为它会隐藏逻辑错误,我研究了@yak的想法。这在嵌套的for循环中工作得很好,但不是很优雅。另一种方法是在下一次循环之前检查条件:

b = None
for a in range(10):
    if something(a, b): # should never = True if b is None
        break
    for b in range(20):
        pass

这可能并不适用于所有地方,但具有适应性,如果需要,它的优点是允许复制条件,而不是潜在的结果。

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

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

这使用了for / else结构:为什么python在for和while循环之后使用'else' ?

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

这里的continue语句很神奇。它在for-else从句中。根据定义,如果没有内部断裂,就会发生这种情况。在这种情况下,继续巧妙地绕过外部中断。

PEP 3136建议标记中断/继续。Guido拒绝了它,因为“需要这个功能的复杂代码非常罕见”。不过,PEP确实提到了一些变通方法(比如异常技术),而Guido认为在大多数情况下,使用return进行重构会更简单。