switchcase语句python(switchcase语句用法 default放前面)

http://www.itjxue.com  2023-01-27 00:07  来源:未知  点击次数: 

Python里怎么实现switch case

python没有swich语句,可以使用if语句替代:

if a == 1:

pass

elif a==2:

pass

else:

pass

Python那些优雅的写法:switch-case

实际上Python是没有所谓的 switch case 写法的,熟悉C艹和Java的同学可能已经习惯了用 switch case 结构去优雅的处理一些事情,比如这样:

但是在Python中,官方对 switch case 的需求是这样回复的:

" You can do this easily enough with a sequence of if... elif... elif... else. There have been some proposals for switch statement syntax, but there is no consensus (yet) on whether and how to do range tests. "

感觉有点low。

可用字典方法解决这个问题:

为什么Python中没有Switch/Case语句

为了语法统一,可以使用下面的if代替switch

if?a==1:

????pass

elif?a==2:

????pass

elif?a==3:

????pass

(责任编辑:IT教学网)

更多

推荐Fireworks教程文章