打破多个嵌套的while循环

时间:2017-06-02 05:39:25

标签: python

如果我有一段看起来像这样的代码:

for ship in ships.shipLengths.key():
    while(True):
        # Code
        while(True):
            # Code
            while(True):
                # Code

如果我目前处于第3阶段,那么循环是否有办法让我回到第一个while循环?

1 个答案:

答案 0 :(得分:0)

我同意@Aluan和@Daniel这样编写代码不是一个好习惯。

无论如何,如果你还想这样做,可以采用以下方式:

x = True
for ship in ships.shipLengths.key():
    while condition1:
        # Code
        while condition2 and x:
            # Code
            while condition3 and x:
                # Code
                if goto_1st_while:
                    x = False
                    continue
                # The code here will not run when goto_1st_while is True
            if not x:
                continue
            # The code here will not run when goto_1st_while is True