SyntaxError:使用匹配大小写时语法无效

Jav*_*Cry 43 python pattern-matching

我一直在尝试使用匹配大小写而不是一百万个 IF 语句,但我尝试的任何操作都会返回错误:

    match http_code:
          ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

我还尝试过测试我发现的示例,这些示例也会返回此错误,包括以下错误:

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")
Run Code Online (Sandbox Code Playgroud)

我知道匹配案例对于 python 来说是相当新的,但我使用的是 3.10,所以我不确定为什么它们总是返回这个错误。

小智 38

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)
Run Code Online (Sandbox Code Playgroud)

-V或者通过将或传递给 Python在命令行检查版本--version。例如,在系统上 wherepython指的是 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.
>>> 
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅如何检查正在运行我的脚本的 Python 版本?以及我安装了哪个版本的 Python?

如果您尝试使用虚拟环境,请确保它已激活(Linux/Mac howtoWindows (CMD) howtoWindows (Powershell) howto使用 PyCharm)。

在 3.10 中,代码有效:

import sys
assert sys.version_info >= (3, 10)
Run Code Online (Sandbox Code Playgroud)