if…else

  • 最常见的 else
1
2
3
4
if 1 > 0:
    pass
else:
    pass

for else

  • for 循环中
  • 只有 for 循环结束了才执行, 注意空循环也会执行
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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 在所有状态下都会执行
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
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