给定以下代码(不起作用):
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
有办法解决这个问题吗?还是我必须先检查一次,跳出输入循环,然后再检查一次,如果用户满意,再跳出外部循环?
这是另一种简短的方法。缺点是你只能打破外部循环,但有时这正是你想要的。
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从句中。根据定义,如果没有内部断裂,就会发生这种情况。在这种情况下,继续巧妙地绕过外部中断。
这是另一种简短的方法。缺点是你只能打破外部循环,但有时这正是你想要的。
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从句中。根据定义,如果没有内部断裂,就会发生这种情况。在这种情况下,继续巧妙地绕过外部中断。
你可以使用一个标志来打破循环:
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。