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

问题描述 投票:0回答:2

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

    match http_code:
          ^
SyntaxError: invalid syntax

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

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")

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

python pattern-matching
2个回答
39
投票

match
/
case
语法,也称为结构模式匹配,仅在Python版本3.10中引入。请注意,按照标准约定,
.
后面的数字不是小数,而是版本号的单独“部分”。 Python 3.9(以及 3.8、3.7 等)出现在 Python 3.10 之前,并且不支持该语法。 Python 3.11(及更高版本)do支持该语法。 虽然前面一行中的语法错误可能直到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 howtoWindows (CMD) howtoWindows (Powershell) howto

using 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"

问题是 Python 版本使用的系统不是一个好的系统,可能会让用户感到困惑。

3.10 似乎比 3.8 更老(我将它们四舍五入为 3.80 x 3.10)
为什么不跳到 Python 4.0 而不是 3.10 ?

0
投票
如果Python使用3.0.8而不是3.8和3.10会更好吗

© www.soinside.com 2019 - 2024. All rights reserved.