Python 中的else
if…else
- 最常见的
else
if 1 > 0:
pass
else:
pass
for else
- for 循环中
- 只有 for 循环结束了才执行, 注意空循环也会执行
for i in range(3):
print(i)
else:
print("end")
# 0
# 1
# 2
# end
for i in range(3):
print(i)
if i == 1:
break
else:
print("end")
# 0
# 1
try… else
- 这个就很好理解了,
else
只会在try
未发生任何异常的时候执行 finally
在所有状态下都会执行
try:
1
except Exception as e:
print(e)
else:
print("else")
finally:
print("finally")
# else
# finally
try:
1/0
except Exception as e:
print(e)
else:
print("else")
finally:
print("finally")
# division by zero
# finally