为什么我在 Python 中收到使用 match 的错误消息?

Why am I getting an error message in Python for using match?

提问人:lexi_roro 提问时间:7/29/2023 更新时间:7/29/2023 访问量:140

问:

当我键入单词 Match 时,我在 Python 中收到语法错误。我什至拥有最新版本的 Python 3.11.4

http_status = 200

if http_status == 200 or http_status == 201:
    print("success")
elif http_status == 400:
    print("Bad request")
elif http_status == 404:
    print("Not found")
elif http_status == 500 or http_status == 501:
    print("Server Error")
else: 
    print("Unknown")

match http_status:
    case 200:
        print("success")

错误信息:

比赛http_status: ^ SyntaxError:语法无效

我检查了我的语法是否正确,确实如此。我不确定我拥有的版本是否不再接受匹配

python switch-statement 匹配

评论

4赞 Tom Karzes 7/29/2023
您确定您运行的 Python 版本是 3.11.4,而不是早期安装的版本吗?添加到你的代码中,看看它说了什么。print(sys.version)
0赞 Codist 7/29/2023
您的代码不会在 Python 3.11.4 中引发 SyntaxError 异常。事实上,只有当您的 Python 版本低于 3.10 时(即引入 match/case 时),才会发生这种情况
0赞 lexi_roro 7/31/2023
@TomKarzes 这是我得到的 print(sys.error) 成功 3.9.6(默认,2023 年 5 月 7 日,23:32:44)[Clang 14.0.3 (clang-1403.0.22.14.1)] 当我在终端中输入 python3 -- version 时,我得到 3.11.4
1赞 Tom Karzes 7/31/2023
@lexi_roro 我猜你的意思是,不是.因此,您有两个不同的 Python 安装。当你以交互方式运行 Python 时,你会得到 3.11.4,但当你运行 Python 程序时,你会得到 3.9.6。这解释了你的问题。你是如何运行你的程序的?您需要修复它,使其使用 3.11.4 而不是 3.9.6。sys.versionsys.error
0赞 lexi_roro 7/31/2023
@TomKarzes 谢谢汤姆的帮助!我弄清楚了这个问题。当我自己打开 Visual Studio Code 应用程序(不使用终端)时,它推荐了 Python 解释器 3.9.6。在我的终端上,当我输入“python3 --version”然后输入“code .”时,它打开了 Visual Studio Code 并显示了使用 3.11.4 解释器的选项

答: 暂无答案