Python 打破多个嵌套while循环
如果我有一个如下代码体:Python 打破多个嵌套while循环,python,Python,如果我有一个如下代码体: for ship in ships.shipLengths.key(): while(True): # Code while(True): # Code while(True): # Code 如果我目前在第三个while循环中,有没有办法回到第一个while循环?我同意@Aluan和@Daniel的观点,用这种方式编写代码不是一个好的做法 无论如何
for ship in ships.shipLengths.key():
while(True):
# Code
while(True):
# Code
while(True):
# Code
如果我目前在第三个while循环中,有没有办法回到第一个while循环?我同意@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
请不要这样写代码,它的可读性很差。使用函数代替每个循环的主体。在函数中编写代码,以便可以使用return退出多个循环在下一个循环中使用break可能重复continue不好,如果使用continue,则无法退出循环,而只能继续其运行是,但当x为False时,将退出。