当前位置: 移动技术网 > IT编程>脚本编程>Python > python技巧 switch case语句

python技巧 switch case语句

2018年11月21日  | 移动技术网IT编程  | 我要评论

朴有亚,生长素的生理作用ppt,97seyise

不同于c语言和shell,python中没有switch case语句,关于为什么没有,官方的是这样的

使用python模拟实现的方法:

 

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

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网