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)()            # 执行对应的函数,如果没有就执行默认的函数

posted @ 2021-12-21 20:06  尤利阳  阅读(12601)  评论(0编辑  收藏  举报