- for+else
- def else1(num):
- for i in range(num):
- if(i>10):
- break
- print(i)
- else:
- print("over") #当 for 循环正常结束时, 会执行该条语句
- else1(5)
- print("##"*20)
- else1(20)
结果:
- 0
- 1
- 2
- 3
- 4
- over
- ########################################
- 0
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- while+else
- def else2(num):
- while num> 0:
- if(num==10):
- break
- num-=1
- print(num)
- else:
- print("over") #当 while 循环正常结束时, 会执行该条语句
- else2(5)
- print("##"*20)
- else2(20)
结果:
- 4
- 3
- 2
- 1
- 0
- over
- ########################################
- 19
- 18
- 17
- 16
- 15
- 14
- 13
- 12
- 11
- 10
- try+else
- def ex(num):
- if(num==10):
- raise BaseException("BaseException!")
- def else3(num):
- try:
- for i in range(num):
- ex(i)
- print(i)
- except BaseException as msg:
- print(msg)
- else:
- print("over")
- finally:
- print("end")
- else3(5)
- print("##"*20)
- else3(20)
结果:
- 0
- 1
- 2
- 3
- 4
- over
- end
- ########################################
- 0
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- BaseException!
- end
来源: http://www.bubuko.com/infodetail-3301513.html