鐵人賽第二天,先來做一些簡單的暖身吧!介紹一下比較罕見的條件控制:while 搭配 else 與 for 搭配 else
"""
'else' can use with 'while'!
however, no 'elif' ...
"""
flag = 1
while flag < 5:
print(flag, end=' ')
flag += 1
else:
print('\nend of while loop')
1 2 3 4
end of while loop
觀看以上程式碼的輸出可以發現,在 while 迴圈跑完後,執行 else 的部分。
但⋯⋯如果只是這樣的話,不寫 else,直接執行 print 不是更好?
客倌別急,特別的地方來了:
flag = 1
while flag < 5:
print(flag, end=' ')
flag += 1
if flag == 3:
break
else:
print('\nend of while loop')
1 2
發現了嗎?
當 while 迴圈因為 break 或 return 中斷時,下面的 else 是不會執行的!
這在一些特殊情境下可派上用場,比如你要寫一個簡單的「猜水果遊戲」,玩家猜到五種水果中的其中一種贏得遊戲,否則輸掉遊戲,玩家有五次機會,則可以這樣寫:
chance = 5
fruits = {"apple", "banana", "cherry", "durian"}
while chance:
ans = input('Guess the fruit')
print(f"Your guess is {ans}")
if ans in fruits:
print("You win!")
break
chance -= 1
else:
print("You lose!")
Your guess is grape
Your guess is orange
Your guess is banana
You win!
如何,相較使用一個變數額外紀錄贏或輸的狀態,這樣 while/else 的搭配是否又更優雅了呢?
for/else 也是一樣的概念歐!自己寫寫看吧!
最後補充一個大家大概有印象,但平常寫 code 比較少用到的 finally:
try...except...finally
finally will always execute!
pivot = 3
msg = ''
while True:
try:
1 / pivot
except ZeroDivisionError:
print('Divided by zero.')
msg = 'even break before.'
finally:
print(pivot, f'this is always printed {msg}')
pivot -= 1
3 this is always printed
2 this is always printed
1 this is always printed
Divided by zero.
0 this is always printed even break before.
可以看到,不管前面是否已經 break,finally 的段落永遠會被執行
這在最後要關閉物件或清除資源時可以用上。
好啦,第二天先到這邊,我們明天見!