方法1:自定义异常 # -*- coding:utf-8 -*- """ 功能:python跳出循环 """ # 方法1:自定义异常 class Getoutofloop(Exception): pass try: for i in range(5): for j in range(5): if i == j == 2: raise Getoutofloop() else: print i, '----', j except Getoutoflo
Python 本身没有“break n” 和“goto” 的语法,这也造成了Python 难以跳出多层(特定层数)循环.下面是几个跳出多层(特定层数)循环的tip. 1.自定义异常 class getoutofloop(Exception): pass try: for i in range(5): for j in range(5): for k in range(5): if i == j == k == 3: raise getoutofloop() else: print i, '-
Alex大神的需求:三层循环,在最内层循环中使用break,让所有循环结束; # 编辑者:闫龙 i=1; count=0; while 1==i : while 1==i: while 1==i: count+=1; print("我循环了",count,"次"); if count == 5: print("我要退出了"); i = 10000; break; print("所有循环已跳出"); 说实话,这个东西特么的,还真
跳出多层循环:三层循环,最里层直接跳出3层 在Python中,函数运行到return这一句就会停止,因此可以利用这一特性,将功能写成函数,终止多重循环 def work(): for i in range(5): print("i=", i) for j in range(5): print("--j=", j) for k in range(5): if k<2: print("------>k=", k) else: return