给定以下代码(不起作用):
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
有办法解决这个问题吗?还是我必须先检查一次,跳出输入循环,然后再检查一次,如果用户满意,再跳出外部循环?
另一种将迭代减少到单层循环的方法是使用生成器,这也在python参考中指定
for i, j in ((i, j) for i in A for j in B):
print(i , j)
if (some_condition):
break
您可以将它扩展到循环的任意级别
缺点是您不能再只打破单个级别。要么全有,要么全无。
另一个缺点是它不能与while循环一起工作。我最初想在Python上发布这个答案-“break”跳出所有循环,但不幸的是,它被关闭为这个循环的副本
你可以使用一个标志来打破循环:
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。
首先,普通的逻辑是有用的。
如果由于某种原因,终止条件无法确定,例外是一个后备计划。
class GetOutOfLoop( Exception ):
pass
try:
done= False
while not done:
isok= False
while not (done or isok):
ok = get_input("Is this ok? (y/n)")
if ok in ("y", "Y") or ok in ("n", "N") :
done= True # probably better
raise GetOutOfLoop
# other stuff
except GetOutOfLoop:
pass
对于这个特定的示例,可能不需要异常。
另一方面,在字符模式应用程序中,我们经常有“Y”、“N”和“Q”选项。对于"Q"选项,我们要立即退出。这是比较特殊的。