python-else妙用
作者:互联网
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2022/8/12 18:50
# @Author : xxx
# @Software: PyCharm
def for_else_test():
'''测试for...else...意思是,for运行完成后运行else'''
list = [1,2,3,4,5]
for i in list:
if i%2==0:
print(i)
# else:
# break
else:
# 如果上边的for正常执行完成,else就会执行,否则else是不执行的
print("执行for了else")
def while_else_test():
'''测试while...else...意思是,while条件为假退出时执行else'''
active_flag = True
list = {
'name': 'zhangsan',
'age': 20,
'score': 90
}
while active_flag:
if list.get('name')=='zhangsan':
# active_flag = False
print('张三来了,大家快跑!!!')
else:
print("我晓得张三来了,并且执行了else语句~")
def try_else_test():
'''测试try...else...意思是,try没有报错就执行else'''
try:
div = 1/1
print(div)
except Exception as _:
print("抛出错误,并且不去执行else")
else:
print("tru正常运行,没有遇到什么问题")
if __name__ == '__main__':
# for_else_test()
# while_else_test()
try_else_test()
标签:妙用,...,python,else,try,test,while,print 来源: https://www.cnblogs.com/spider3658/p/16581099.html