您的位置:首页 > 编程语言 > Python开发

Python else语句

2017-02-26 12:44 323 查看

Python else语句

python的else和其他语言不通,通常if-else是一起使用的,但是python中的else语句还有其他几种用法。

用法1 if-else

若果
if
条件为真则运行
if
中的语句,如果为假则运行
else
中的语句。

if True:
print('True')
else:
print('False')
'''
结果:True
'''


用法2 try-except-else

如果
try
中的语句有异常则运行
except
中的代码,没有异常则运行
else
的代码

try:
1/2
except Exception as e:
print(e)
else:
print('else')
'''
结果:else
'''


用法3 for else

如果
for
正常运行完毕则会执行
else
,如果
for
因为
break
跳出循环则
else
不会执行。

for x in range(5):
print(x)
else:
print("normal end")
'''
结果:
0
1
2
3
4
normal end
'''
for x in range(5):
print(x)
break
else:
print("normal end")
'''
结果:0
'''
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: