python中else的用法
for+else
1 def else1(num): 2 for i in range(num): 3 if(i>10): 4 break 5 print(i) 6 else: 7 print("over") #当for循环正常结束时,会执行该条语句 8 9 10 else1(5) 11 print("##"*20) 12 else1(20) 13 14 结果: 15 16 0 17 1 18 2 19 3 20 4 21 over 22 ######################################## 23 0 24 1 25 2 26 3 27 4 28 5 29 6 30 7 31 8 32 9 33 10
while+else
1 def else2(num): 2 while num > 0: 3 if(num==10): 4 break 5 num-=1 6 print(num) 7 else: 8 print("over") #当while循环正常结束时,会执行该条语句 9 10 11 else2(5) 12 print("##"*20) 13 else2(20) 14 15 结果: 16 4 17 3 18 2 19 1 20 0 21 over 22 ######################################## 23 19 24 18 25 17 26 16 27 15 28 14 29 13 30 12 31 11 32 10
try+else
1 def ex(num): 2 if(num==10): 3 raise BaseException("BaseException!") 4 5 def else3(num): 6 try: 7 for i in range(num): 8 ex(i) 9 print(i) 10 except BaseException as msg: 11 print(msg) 12 else: 13 print("over") 14 finally: 15 print("end") 16 17 else3(5) 18 print("##"*20) 19 else3(20) 20 21 结果: 22 0 23 1 24 2 25 3 26 4 27 over 28 end 29 ######################################## 30 0 31 1 32 2 33 3 34 4 35 5 36 6 37 7 38 8 39 9 40 BaseException! 41 end
本文来自博客园,作者:月色深潭,交流群:733423266,转载请注明原文链接:https://www.cnblogs.com/moonpool/p/11921368.html