"match" Statement for Pattern Match

This section provides a quick introduction of 'match' statement, which selects a block of sub-statements to execute based on pattern match algorithms.

What Is "match" Statement? A "match" statement is a compound statement that selects a block of sub-statements to execute based on pattern match algorithms. "match" statements were introduced in 2021 in Python 3.10.

Here is the syntax of "match" statements:

match SUBJECT:
    case PATTHEN_1 [if CONDITION_1]:
        SUITE_1
    case PATTHEN_2 [if CONDITION_2]:
        SUITE_2
    ...
    case _:
        SUITE_n

Logically, a "match" statement written in the above syntax is equivalent to the following code using "if" statements:

if SUITE_1_matches_SUBJECT [and CONDITION_1]:
    SUITE_1
elif SUITE_2_matches_SUBJECT [and CONDITION_2]:
    SUITE_2
...
else
    SUITE_n

I don't have Python 3.10 installed yet. So I am not able to run any test on "match" statements. But you can look at the following example given in the Python 3.10 manual.

>>> flag = False
>>> match (100, 200):
...    case (100, 300):  # Mismatch: 200 != 300
...        print('Case 1')
...    case (100, 200) if flag:  # Successful match, but guard fails
...        print('Case 2')
...    case (100, y):  # Matches and binds y to 200
...        print(f'Case 3, y: {y}')
...    case _:  # Pattern not attempted
...        print('Case 4, I match anything!')
...
Case 3, y: 200

Table of Contents

 About This Book

 Running Python Code Online

 Python on macOS Computers

 Python on Linux Computers

 Built-in Data Types

 Variables, Operations and Expressions

Statements - Execution Units

 What Is Statement

 "pass" Statement - Do Nothing Statement

 Expression Statement - One Expression Only

 "=" Statement - Assignment Statement

 "del" Statement - Delete Statement

 "import" Statement to Load Modules

 "if" Statement for Conditional Execution

 "while" Statement for Execution Loop

 "for" Statement for Iterative Execution

 "try" Statement to Catch Execution

 "with" Statement for Context Manager

"match" Statement for Pattern Match

 Function Statement and Function Call

 Iterators, Generators and List Comprehensions

 Classes and Instances

 Modules and Module Files

 Packages and Package Directories

 "sys" and "os" Modules

 "pathlib" - Object-Oriented Filesystem Paths

 "pip" - Package Installer for Python

 SciPy.org - Python Libraries for Science

 pandas - Data Analysis and Manipulation

 Anaconda - Python Environment Manager

 Jupyter Notebook and JupyterLab

 References

 Full Version in PDF/EPUB