當需要用到3個及以上的if...elif...else時就要考慮該方法進行簡化
通過將函數名稱當做字典的值,利用字典的關鍵字查詢,可以快速定位函數,進行執行
【場景】用戶查詢信息,輸入fn查詢,執行對應函數
1 # 簡單用十個函數模擬查詢函數 2 def fun1(): 3 print("查詢1") 4 def fun2(): 5 print("查詢2") 6 def fun3(): 7 print("查詢3") 8 def fun4(): 9 print("查詢4") 10 def fun5(): 11 print("查詢5") 12 def fun6(): 13 print("查詢6") 14 def fun7(): 15 print("查詢7") 16 def fun8(): 17 print("查詢8") 18 def fun9(): 19 print("查詢9") 20 def fun10(): 21 print("查詢10")
傳統方法 if...elif...elif...else(寫起來很麻煩)
choice = input("請輸入查詢內容fn:") if choice == 'f1': fun1() elif choice == 'f2': fun2() elif choice == 'f3': fun3() elif choice == 'f4': fun4() elif choice == 'f5': fun5() elif choice == 'f6': fun6() else: fun10() """ 請輸入查詢內容fn:f1 查詢1 """
將函數當做字典的值
# 創建字典 info = {'f1': fun1, 'f2': fun2, 'f3': fun3, 'f4': fun4, 'f5': fun5, 'f6': fun6, 'f7': fun7, 'f8': fun8, 'f9': fun9, 'f10': fun10} choice = input("請輸入查詢內容fn:") info_value = info.get(choice) print(info_value) if info_value: info_value() else: print('輸入異常') """ 請輸入查詢內容fn:f11 None 輸入異常 """
獲取字典中的value 使用get()函數,這樣當關鍵字不存在時,返回的值的None,不會導致程序報錯