通过标志位跳出多层循环
break只能跳出本层循环,若要跳出多层循环,可定义个标志位break_flag
跳出多层for循环:
break_flag=False for i in range(10): print("爷爷层",i) for j in range(10): print("爸爸层",j) if j == 3: break_flag=True break for k in range(10): print("孙子层",k) if k ==2: break_flag=True break if break_flag: print("儿子蒙了,不活了...") break if break_flag: print("儿子蒙了,不活了...") break
跳出while多层循环:
break_flag=False count=0 while break_flag==False: print("爷爷层...") while break_flag==False: print("爸爸层...") while break_flag==False: count+=1 if count>10: break_flag=True print("孙子层...") print("keep going...")