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

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

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


当前回答

可能像下面这样的小技巧会做,如果不喜欢重构成函数

增加了1个break_level变量来控制while循环条件

break_level = 0
# while break_level < 3: # if we have another level of nested loop here
while break_level < 2:
    #snip: print out current state
    while break_level < 1:
        ok = get_input("Is this ok? (y/n)")
        if ok == "y" or ok == "Y": break_level = 2 # break 2 level
        if ok == "n" or ok == "N": break_level = 1 # break 1 level

其他回答

引入一个新变量作为“循环打破器”。首先给它赋值(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   # <--- !

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

尝试使用无限发电机。

from itertools import repeat
inputs = (get_input("Is this ok? (y/n)") for _ in repeat(None))
response = (i.lower()=="y" for i in inputs if i.lower() in ("y", "n"))

while True:
    #snip: print out current state
    if next(response):
        break
    #do more processing with menus and stuff

解决方法有两种

举个例子:这两个矩阵相等/相同吗? 矩阵x1和矩阵x2是相同大小的,n,二维矩阵。

第一个解决方案,没有函数

same_matrices = True
inner_loop_broken_once = False
n = len(matrix1)

for i in range(n):
    for j in range(n):

        if matrix1[i][j] != matrix2[i][j]:
            same_matrices = False
            inner_loop_broken_once = True
            break

    if inner_loop_broken_once:
        break

第二个解决方案,用函数

这是我案子的最终解决方案。

def are_two_matrices_the_same (matrix1, matrix2):
    n = len(matrix1)
    for i in range(n):
        for j in range(n):
            if matrix1[i][j] != matrix2[i][j]:
                return False
    return True

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

你可以使用一个标志来打破循环:

if found:
  break

这里,'found'是标志,你最初将它设置为False,然后在循环中使用这段代码。

found = False
for table_height in range(500):
  if found:
    break

下面是三个for循环的完整代码:

found = False
for table_height in range(500):
  if found:
    break
  for cat_height in range(500):
    if found:
      break

    for tort_height in range(500):
      equation1 = table_height + cat_height == tort_height + 170
      equation2 = table_height + tort_height == cat_height + 130
      if equation1 and equation2:
        print('table', table_height, '  cat', cat_height, '  tortoise', tort_height)
        found = True
        break

在这段代码中,如果等式1和等式2为True,它将设置'found'标志为True,并跳出最里面的for循环,它也将跳出其他两个for循环,因为'found'为True。