Python switch(多分支选择)的实现

原文链接: http://www.cnblogs.com/dbf-/p/10601216.html

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 case4():                            # 第四种情况执行的函数
    print('This is the case4')


def case5():                            # 第五种情况执行的函数
    print('This is the case5')


def default():                          # 默认情况下执行的函数
    print('No such case')

switch = {'case1': case1,                # 注意此处不要加括号
          'case2': case2,                # 注意此处不要加括号
          'case3': case3,                # 注意此处不要加括号
          'case4': case4,                # 注意此处不要加括号
          'case5': case5                 # 注意此处不要加括号
          }

choice = 'case1'                         # 获取选择
switch.get(choice, default)()            # 执行对应的函数,如果没有就执行默认的函数

switch.get(choice, default)() 先去字典中查找 key 之后执行以 key 对应的 value 为函数名的函数,如果没有找到相应的 key 就执行默认函数。

转载于:https://www.cnblogs.com/dbf-/p/10601216.html

猜你喜欢

转载自blog.csdn.net/weixin_30399871/article/details/94919795