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

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

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


当前回答

尽量减少对OP的问题的改变,我只是在打破第一个for循环之前添加了一个标志,并检查外部循环上的标志,看看我们是否需要再次刹车。

break_2 = False
while True:
    # Snip: print out current state
    if break_2: break
    while True:
        ok = get_input("Is this ok? (y/n)")
        if ok.lower() == "y": break_2 = True
        if break_2: break
        if ok.lower() == "n": break
    # Do more processing with menus and stuff

其他回答

我解决这个问题的方法是定义一个变量,该变量被引用来确定你是否进入下一关。在这个例子中,这个变量叫做shouldbreak。

Variable_That_Counts_To_Three=1
while 1==1:
    shouldbreak='no'
    Variable_That_Counts_To_Five=0
    while 2==2:
        Variable_That_Counts_To_Five+=1
        print(Variable_That_Counts_To_Five)
        if Variable_That_Counts_To_Five == 5:
            if Variable_That_Counts_To_Three == 3:
                shouldbreak='yes'
            break
    print('Three Counter = ' + str(Variable_That_Counts_To_Three))
    Variable_That_Counts_To_Three+=1
    if shouldbreak == 'yes':
        break

print('''
This breaks out of two loops!''')

这为您希望程序中断的确切方式提供了大量控制,允许您选择何时中断以及下降多少层。

keeplooping = True
while keeplooping:
    # Do stuff
    while keeplooping:
          # Do some other stuff
          if finisheddoingstuff():
              keeplooping = False

或者类似的东西。

您可以在内部循环中设置一个变量,并在内部循环退出后立即在外部循环中检查它,如果合适的话可以中断。我有点喜欢GOTO方法,前提是你不介意使用愚人节的笑话模块——它不是python的,但它确实有意义。

解决方法有两种

举个例子:这两个矩阵相等/相同吗? 矩阵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

这不是最漂亮的方法,但在我看来,这是最好的方法。

def loop():
    while True:
    #snip: print out current state
        while True:
            ok = get_input("Is this ok? (y/n)")
            if ok == "y" or ok == "Y": return
            if ok == "n" or ok == "N": break
        #do more processing with menus and stuff

我很确定你也可以用递归解出一些东西,但我不知道这对你来说是不是一个好选择。

从语言层面上没有办法做到这一点。有些语言 一个goto其他人有一个需要争论的休息,python没有。 最好的选择是: 设置一个由外部循环检查的标志,或设置外部循环 循环条件。 将循环放入函数中,并使用return立即跳出所有循环。 重新规划你的逻辑。

这要归功于Vivek Nagarajan,他从1987年开始成为程序员


使用函数

def doMywork(data):
    for i in data:
       for e in i:
         return 

使用国旗

is_break = False
for i in data:
   if is_break:
      break # outer loop break
   for e in i:
      is_break = True
      break # inner loop break