前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python技巧 switch case

python技巧 switch case

作者头像
py3study
发布2020-01-20 10:38:50
5520
发布2020-01-20 10:38:50
举报
文章被收录于专栏:python3

不同于C语言和SHELL,python中没有switch case语句,关于为什么没有,官方的解释是这样的 使用Python模拟实现的方法:

代码语言:javascript
复制
def switch_if(fun, x, y):
    if fun == 'add':
        return x + y
    elif fun == 'sub':
        return x - y
    elif fun == 'mul':
        return x * y
    elif fun == 'div':
        return x / y
    else:
        return None


def switch_dict(fun, x, y):
    return {
        'add': lambda: x + y,
        'sub': lambda: x - y,
        'mul': lambda: x * y,
        'div': lambda: x / y,
    }.get(fun,None)()


print("switch_if('add',1,2):",switch_if('add',1,2))
print("switch_if('sub',1,2):",switch_if('sub',1,2))
print("switch_if('mul',1,2):",switch_if('mul',1,2))
print("switch_if('div',1,2):",switch_if('div',1,2))

print("switch_dict('add',1,2):",switch_dict('add',1,2))
print("switch_dict('sub',1,2):",switch_dict('sub',1,2))
print("switch_dict('mul',1,2):",switch_dict('mul',1,2))
print("switch_dict('div',1,2):",switch_dict('div',1,2))
switch_if('add',1,2): 3
switch_if('sub',1,2): -1
switch_if('mul',1,2): 2
switch_if('div',1,2): 0.5
switch_dict('add',1,2): 3
switch_dict('sub',1,2): -1
switch_dict('mul',1,2): 2
switch_dict('div',1,2): 0.5
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/04/09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档