Python 中沒有 switch/case 語法,如果使用 if/elif/else 會出現代碼過長、不清晰等問題。
而借助字典就可以實現 switch 的功能
def case1(): # 第一種情況執行的函數
print('This is the case1')
def case2(): # 第二種情況執行的函數
print('This is the case2')
def case3(): # 第三種情況執行的函數
print('This is the case3')
def default(): # 默認情況下執行的函數
print('No such case')
switch = {'case1': case1, # 注意此處不要加括號
'case2': case2,
'case3': case3,
}
choice = 'case1' # 獲取選擇
switch.get(choice, default)() # 執行對應的函數,如果沒有就執行默認的函數
