match
/case
语法,也被称为结构模式匹配,仅在Python 3.10版本中引入。请注意,遵循标准惯例,.
后面的数字不是十进制,而是版本号的一个单独的“部分”。Python 3.9(以及3.8、3.7等)在Python 3.10之前,不支持该语法。Python 3.11(及更高版本)支持该语法。
虽然可能会出现在先前行上的语法错误直到使用match
关键字才被发现,但这种类型的语法错误更多地表明Python版本至少不是3.10
。
如果Python版本过低而不支持match
/case
,则此代码将失败并出现断言错误:
import sys
assert sys.version_info >= (3, 10)
或者在命令行中检查版本,通过传递-V
或--version
给Python。例如,在一个系统中,python
指的是3.8安装(在那里它不起作用):
$ python --version
Python 3.8.10
$ python
Python 3.8.10 (default, Nov 14 2022, 12:59:47)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
如需更多详细信息,请参见如何检查正在运行脚本的Python版本?和我安装了哪个版本的Python?。
如果您正在尝试使用虚拟环境,请确保已激活它(Linux/Mac howto,Windows (CMD) howto,Windows (Powershell) howto,使用PyCharm)。
在3.10中,该代码可以正常工作:
Python 3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> http_code = "418"
>>> match http_code:
... case "200":
... print("OK")
... case "404":
... print("Not Found")
... case "418":
... print("I'm a teapot")
... case _:
... print("Code not found")
Out[1]: "I'm a teapot"
match-case
在Python的后续版本中已被弃用吗? - Jiwon