Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be
on-topic
here, this one was resolved in a way less likely to help future readers.
Closed
1 year ago
.
The community reviewed whether to reopen this question
9 months ago
and left it closed:
Original close reason(s) were not resolved
I've been trying to use a match case instead of a million IF statements, but anything I try returns the error:
match http_code:
SyntaxError: invalid syntax
I've also tried testing examples I've found, which also return this error, including this one:
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")
I'm aware that match cases are quite new to python, but I'm using 3.10 so I'm not sure why they always return this error.
–
The match
/case
syntax, otherwise known as Structural Pattern Matching, was only introduced in Python version 3.10. Note well that, following standard conventions, the number after the .
is not a decimal, but a separate "part" of the version number. Python 3.9 (along with 3.8, 3.7 etc.) comes before Python 3.10, and does not support the syntax. Python 3.11 (and onward) do support the syntax.
While it's possible that a syntax error on an earlier line wouldn't be noticed until the match
keyword, this sort of syntax error is much more a sign that the Python version isn't at least 3.10
.
This code will fail with an assertion if the Python version is too low to support match
/case
:
import sys
assert sys.version_info >= (3, 10)
Or check the version at the command line, by passing -V
or --version
to Python. For example, on a system where python
refers to a 3.8 installation (where it won't work):
$ 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.
For more details, see How do I check which version of Python is running my script? and Which version of Python do I have installed?.
If you're trying to use a virtual environment, make sure that it's activated (Linux/Mac howto, Windows (CMD) howto, Windows (Powershell) howto, using PyCharm).
In 3.10, the code works:
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"