Skip to content
On this page

Pattern Matching

When using if ... elif ... elif ... else ... to make conditional judgments, the code can become lengthy and less readable. If you need to match several cases for a variable, you can use the match statement.

For example, if a student's score can only be A, B, or C, using the if statement would look like this:

python
score = 'B'
if score == 'A':
    print('score is A.')
elif score == 'B':
    print('score is B.')
elif score == 'C':
    print('score is C.')
else:
    print('invalid score.')

The same logic can be rewritten with the match statement:

python
score = 'B'

match score:
    case 'A':
        print('score is A.')
    case 'B':
        print('score is B.')
    case 'C':
        print('score is C.')
    case _:  # The underscore (_) matches any other case
        print('score is ???.')

When using the match statement, we match cases sequentially with case xxx, and we can add a final case _ to represent "any other value." This approach is more readable than using if ... elif ... else ....

Complex Matching

The match statement can match more than just single values; it can match multiple values, ranges, and bind matched values to variables:

python
age = 15

match age:
    case x if x < 10:
        print(f'< 10 years old: {x}')
    case 10:
        print('10 years old.')
    case 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18:
        print('11~18 years old.')
    case 19:
        print('19 years old.')
    case _:
        print('not sure.')

In this example:

  • The first case x if x < 10 matches when age < 10, and assigns the value to the variable x.
  • The second case 10 matches only the value 10.
  • The third case 11 | 12 | ... | 18 matches multiple values using the | separator.
  • The match statement demonstrates the flexibility of case matching.

Matching Lists

The match statement can also match lists, making it very powerful.

Suppose a user has input a command stored as args = ['gcc', 'hello.c']. The following code demonstrates how to use match to parse this list:

python
args = ['gcc', 'hello.c', 'world.c']
# args = ['clean']
# args = ['gcc']

match args:
    # If only 'gcc' appears, report an error:
    case ['gcc']:
        print('gcc: missing source file(s).')
    # If 'gcc' appears and at least one file is specified:
    case ['gcc', file1, *files]:
        print('gcc compile: ' + file1 + ', ' + ', '.join(files))
    # If only 'clean' appears:
    case ['clean']:
        print('clean')
    case _:
        print('invalid command.')
  • The first case ['gcc'] matches when the list contains only the string 'gcc', indicating a missing file name.
  • The second case ['gcc', file1, *files] matches when the first element is 'gcc', the second element is assigned to the variable file1, and the remaining elements are assigned to *files. This indicates at least one file is specified.
  • The third case ['clean'] matches when the list contains only the string 'clean'.
  • The final case _ matches any other cases.

The match statement's rules are very flexible, allowing for concise and clear code.

Pattern Matching has loaded