在即将来到的 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')
现在可以使用类似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