对于大白,else一直用在if语句,是少看代码了,原不知与它搭配的地方还真不少,用起来还真好用。
正文:
1,For-else结构在搜索某些东西并找到它时很有用
for i in mylist:
if i == theflag:
break
process(i)
else:
raise ValueError("List argument missing terminal flag.")
2,Try-catch-else结构
try:
foo()
except Exception:
print("Exception occured")
else:
print("Exception didnt occur")
finally:
print("Always gets here")
3,While-else结构
i = 5
while i > 1:
print("Whil-ing away!")
i -= 1
if i == 3:
break
else:
print("Finished up!")

网友评论