switch(多分支选择)的实现

作者: gu_lao_rou-p 分类: Python 发布时间: 2020-09-20 00:08

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

Warning: Undefined variable $aria_req in /www/wwwroot/l.lvovl.cn/wp-content/themes/JieStyle-Two-master/comments.php on line 26

Warning: Undefined variable $aria_req in /www/wwwroot/l.lvovl.cn/wp-content/themes/JieStyle-Two-master/comments.php on line 27

Warning: Undefined variable $aria_req in /www/wwwroot/l.lvovl.cn/wp-content/themes/JieStyle-Two-master/comments.php on line 28
标签云