#-*- coding=utf-8 -*-
"""如何结束多重循环,在单层循环中,可以用break跳出循环,那两层,三层呢?"""
#用异常:#定义一个异常如果value >= 10,触发异常,切记,当循环在函数中时,#且函数中循环片段后还有代码时,不能直接return,这样会导致函数整体结束#正确的方式为:
importdatetimeclassGt_10(Exception):"""docstring for Gt_10"""
def __init__(self, arg):
self.arg=argdefdoSomething():print("will start doSomething")try:for i in range(20):for k in range(20):for j in range(20):if j >= 10:raise Gt_10("值大于10")else:print(j)exceptGt_10 as e:print(e)print('end doSomething')print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
doSomething()#将循环封装为单独的函数:
def multi_for(*arg,**kwarg):for i in range(20):for k in range(20):for j in range(20):if j >= 10:return
else:print(j)continue
defdoSomething1():print("will start doSomething")
multi_for()print('end doSomething')print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
doSomething1()#for--else#在python中,else不只和if组合,还可以和while,for组合
defdoSomething2():print("will start doSomething")for i in range(20):for k in range(20):for j in range(20):if j >= 10:break
else:print(j)continue
else:continue
break
else:continue
break
print('end doSomething')print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
doSomething2()"""output>>
will start doSomething
0
1
2
3
4
5
6
7
8
9
值大于10
end doSomething
2019-03-25 17:13:09
will start doSomething
0
1
2
3
4
5
6
7
8
9
end doSomething
2019-03-25 17:13:09
will start doSomething
0
1
2
3
4
5
6
7
8
9
end doSomething
2019-03-25 17:13:09"""