switch语句的使用方法 switch语句可以不加判断条件吗?

[更新]
·
·
分类:行业
2104 阅读

switch语句的使用方法

switch语句可以不加判断条件吗?

switch语句可以不加判断条件吗?

不能,case中不得出现变量表达式,只能是字面量的表达式,而且你的值不是0就是1

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