Skip to main content

The Python Match Statement

A match statement chooses what to do based on the value it is given.

When you would otherwise need many if..else statements, match can take their place.

Out of several code blocks, it picks one to run.

Here are the steps:

  • Python evaluates the match expression one time.
  • It then compares the result against the value of each case.
  • When a value matches, the block of code under that case runs.

In the example below, a weekday number decides which day name gets printed:

Example

Prompt
Write a Python program that uses a match statement to print the weekday name based on a day number. Set day to 4 and match cases 1-7 to Monday-Sunday.
Output: complete Python program

Syntax

main.py
match expression:
  case x:
    code block
  case y:
    code block
  case z:
    code block

Default Value

To run a block when no other case has matched, finish with a case whose value is the underscore character _.

Since _ matches anything, its position matters: only as the last case does it act as a default.

Example

Prompt
Write a Python program that uses a match statement with a default case using underscore _. Set day to 4, match 6 for Saturday, 7 for Sunday, and _ for the default message.
Output: complete Python program

Combine Values

One case can test for several values. Separate them with the pipe character |, which acts as an "or" here:

Example

Prompt
Write a Python program that uses the pipe | operator in match cases to combine multiple values. Match days 1-5 as weekday and 6-7 as weekend.
Output: complete Python program

If Statements as Guards

A case can carry an extra condition too. Just add an if statement after its values:

Example

Prompt
Write a Python program that uses if guards in match case statements. Match weekday patterns with month conditions for April and May.
Output: complete Python program