Python switch(多分支選擇)


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)()            # 執行對應的函數,如果沒有就執行默認的函數


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM