如何突破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
continue
continue

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
提交
取消