在单层循环的退出中,使用break即能退出,那么多层循环呢?机智的人们使用flag标识符的方式,例如:
exit_flag = False for i in range(10): if i <5: continue print(i) for j in range(10): print('layer2',j) if j == 6: exit_flag = True #标志位设定为True,跳出内循环 break if exit_flag: #检测标志为为True,跳出循环 break
例子2
a=['a',1,2,3,4] b=['b',1,2,3,4] c=['c',1,2,3,4] d=['d',1,2,3,4] break_flag=0 while break_flag==0: y_n=input('a,yes or no:') if y_n == 'no': break elif y_n == 'yes': for i in a: print(i) while break_flag ==0: y_n_2=input('b,yes or no:') if y_n_2=='no': print('退出') break_flag=1 elif y_n_2=='yes': for j in b: print(j) while break_flag==0: y_n_3=input('c,yes or no:') if y_n_3 == 'no': print('退出。。。') break_flag=1 elif y_n_3 == 'yes': for k in c: print(k) while break_flag == 0: y_n_4 = input('d,yes or no:') if y_n_4=='no': print('退出') break_flag =1 elif y_n_4 =='yes': for n in d: print(n) if break_flag==1: break