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

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

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


当前回答

Break for外层和内部while循环:

while True:
    while True:
        print('Breaks inner "while" loop')
        break # Here
    print('Breaks outer "while" loop')
    break # Here

或者,用if语句中断外部和内部while循环:

while True:
    while True:
        if True:
            print('Breaks inner "while" loop')
            break # Here
    print('Breaks outer "while" loop')
    break # Here

输出:

Breaks inner "while" loop
Breaks outer "while" loop

Break for outer和inner for循环:

for _ in iter(int, 1):
    for _ in iter(int, 1):
        print('Breaks inner "for" loop')
        break # Here
    print('Breaks outer "for" loop')
    break # Here

或者,用if语句打破外部和内部for循环:

for _ in iter(int, 1):
    for _ in iter(int, 1):
        if True:
            print('Breaks inner "for" loop')
            break # Here
    print('Breaks outer "for" loop')
    break # Here

输出:

Breaks inner "for" loop
Breaks outer "for" loop

其他回答

引入一个新变量作为“循环打破器”。首先给它赋值(False,0等),然后,在外层循环中,在终止它之前,将值更改为其他值(True,1,…)。一旦循环退出,让“父”循环检查该值。让我来演示一下:

breaker = False #our mighty loop exiter!
while True:
    while True:
        if conditionMet:
            #insert code here...
            breaker = True 
            break
    if breaker: # the interesting part!
        break   # <--- !

如果你有一个无限循环,这是唯一的出路;对于其他循环,执行速度要快得多。如果你有很多嵌套循环,这也适用。你可以退出全部,也可以只退出一部分。无尽的可能性!希望这对你有所帮助!

下面是一个似乎可以工作的实现:

break_ = False
for i in range(10):
    if break_:
        break
    for j in range(10):
        if j == 3:
            break_ = True
            break
        else:
            print(i, j)

唯一的缺点是你必须在循环之前定义break_。

以下是一个非常简短的版本: 创建名为break_out_nested.py的文件

import itertools
import sys

it = sys.modules[__name__] # this allows us to share variables with break_out_nested.py when we import it 


def bol(*args):
    condi = args[-1] # the condition function
    i = args[:-1] # all iterables 
    for p in itertools.product(*i): # itertools.product creates the nested loop
        if condi(): # if the condition is True, we return 
            return
        yield p # if not, we yield the result 

现在你只需要几行就可以打破嵌套的循环(数据来自Rafiq的例子)

from break_out_nested import it, bol # import what we have just created

# you need to create new variables as attributes of it,
# because break_out_nested has only access to these variables
it.i, it.j, it.k = 1, 1, 1
# the break condition
def cond(): return it.i % 3 == 0 and it.j % 3 == 0 and it.k % 3 == 0

# The condition will be checked in each loop 
for it.i, it.j, it.k in bol(range(1, 6, 1), range(1, 11, 2, ), range(1, 21, 4), cond):
    print(it.i, it.j, it.k)

更多的例子:

def cond(): return it.i + it.j + it.k == 777

it.i, it.j, it.k = 0, 0, 0
for it.i, it.j, it.k in bol(range(100), range(1000), range(10000), cond):
    print(it.i, it.j, it.k)




def cond(): return it.i + it.j + it.k >= 100000

it.i, it.j, it.k = 0, 0, 0
# you dont have to use it.i, it.j, it.k as the loop variables, you can
# use anything you want, but you have to update the variables somewhere
for i, j, k in bol(range(100), range(1000), range(10000), cond):
    it.i, it.j, it.k = i * 10, j * 100, k * 100
    print(it.i, it.j, it.k)

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

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从句中。根据定义,如果没有内部断裂,就会发生这种情况。在这种情况下,继续巧妙地绕过外部中断。

希望这能有所帮助:

x = True
y = True
while x == True:
    while y == True:
         ok = get_input("Is this ok? (y/n)") 
         if ok == "y" or ok == "Y":
             x,y = False,False #breaks from both loops
         if ok == "n" or ok == "N": 
             break #breaks from just one