Skip to content

[Python] The Preview Version 3.10 Support The "match" syntax (switch)

Last Updated on 2021-10-18 by Clay

Switch is a syntax that is supported in many programming languages. It is similar to the if-else syntax, but it executes code for different conditions under a single condition. In many cases it is more intuitive than if-else.

Python has no switch syntax for a long time, but starting from Python 3.10, using match syntax can use conditional divergence similar to switch syntax to execute code in different situations.


Download and Install Python 3.10.0a6

Now (2021/04/03) there is a developer preview version of Python 3.10 available for download and test: https://www.python.org/downloads/release/python-3100a6/


You can go to the Files section at the bottom of the page to select the version that suits your operating system to download.


After the download, install it. (The picture shows the process of Mac OS installation)


After the installation is complete, if you can see the python3.10 in your system, the installation is successful.


Use match syntax for conditional judgment

Integer judgment

Below we use one of the simplest example to demo how to use match in python 3.10 to make numerical judgment.

# coding: utf-8


def main():
    n = 3
    match (n):
        case (1):
            print("OK")
        case (2):
            print("YES")
        case (3):
            print("THANKS")
        case _:
            print("Something error")
        

if __name__ == "__main__":
    main()


Output:

THANKS


The match is followed by the the variable to be judge, and the indented case below is to judge different variable values and execute different blocks of programs for different variable values.

The default in switch syntax is replaced by case _ in Python.


Judgments other than integer judgments

The match in Python is different from a typical switch, and it can even perform functions such as judging the data type of variable:

# coding: utf-8


def main():
    n = "Nice"
    match (n):
        case str() | bytes():
            print("IT'S A STRING")
        case int() | float():
            print("IT'S A NUMBER")
        case list() | dict():
            print("IT's LIST OR DICTIONARY")
        case _:
            print("DEFAULT")
        

if __name__ == "__main__":
    main()


Output:

IT'S A STRING


Since python's match function is not the same as a classic switch, the official even proudly calls it switch 2.0.


References


Read More

Tags:

Leave a Reply