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
'''