The match statement is used to perform different actions based on different conditions.


The Python Match Statement

Instead of writing many if..else statements, you can use the match statement.

The match statement selects one of many code blocks to be executed.

Syntax

match expression:
  case x:
    code block
  case y:
    code block
  case z:
    code block

This is how it works:

The example below uses the weekday number to print the weekday name:

Example

day = 4
match day:
  case 1:
    print("Monday")
  case 2:
    print("Tuesday")
  case 3:
    print("Wednesday")
  case 4:
    print("Thursday")
  case 5:
    print("Friday")
  case 6:
    print("Saturday")
  case 7:
    print("Sunday")

Try it Yourself »


Default Value

Use the underscore character _ as the last case value if you want a code block to execute when there are not other matches:

Example