python 3.10 的新功能 Case / Switch

其它相关内容
问题讨论
回复
头像
shaoziyang
帖子: 3898
注册时间: 2019年 10月 21日 13:48

python 3.10 的新功能 Case / Switch

#1

帖子 shaoziyang »

来自:https://www.blog.pythonlibrary.org/2021 ... n-in-3-10/

在即将来到的 python 3.10 中,增加了Case / Switch 功能。

Code: Select all

if x == 'a':
# Do the thing
elif x == 'b':
# Do the other thing
if x in 'bc':
# Fall-through by not using elif, but now the default case includes case 'a'!
elif x in 'xyz':
# Do yet another thing
else:
# Do the default
 
或者使用字典

代码: 全选

choices = {'a': 1, 'b': 2}
result = choices.get(key, 'default')
这些都是有效的解决方法,而 if–elif–else 是最常用的方式。

现在可以使用类似C语言的方法,这是一个强大的新功能,有很多有趣的用途:

Code: Select all

>>> status_code = 400
>>> match status_code:
... case 400|401|403 :
... print("bad request")
... case 200:
... print("good")
... case _:
print("Something else bad happened") bad request<br>bad request
 
 
 
 

回复

  • 随机主题
    回复总数
    阅读次数
    最新文章