您好,欢迎来到九壹网。
搜索
您的当前位置:首页python中的case语句_python技巧 switch case语句

python中的case语句_python技巧 switch case语句

来源:九壹网

不同于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

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- 91gzw.com 版权所有 湘ICP备2023023988号-2

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务