如何突破Python中的多个循环?给定以下代码(不起作用):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有办法让这件事成功吗?或者,如果用户满意的话,我是否需要做一次检查来打破输入循环,然后另一次,更有限制地,在外部循环中签出所有内容?
3 回答
蛊毒传说
TA贡献1895条经验 获得超3个赞
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
continuecontinue
ABOUTYOU
TA贡献1812条经验 获得超5个赞
class GetOutOfLoop( Exception ):
passtry:
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 stuffexcept GetOutOfLoop:
pass添加回答
举报
0/150
提交
取消
