Python match/case statement (with examples)

Updated: July 18, 2023 By: Khue Post a comment

What is the Point?

The match/case statement in Python is used to implement switch-case like characteristics and if-else functionalities. It was introduced in Python 3.10. The match statement compares a given variable’s value to different shapes, also referred to as patterns, until it fits into one. Once a matching case clause is found, the code inside that case clause is run. If there is no matching case clause for the expression, the code under the default clause case other gets executed.

Here’s the general syntax:

match expression:
    case value1:
        # statements
    case value2:
        # statements
    ...
    case other:
        # statements

Explanation:

  • The match keyword starts a block of code that takes an expression as an argument. The expression can be any valid Python object, such as a variable, a literal, a function call, etc.
  • The case keyword introduces a pattern that is compared to the expression. The pattern can also be any valid Python object or a combination of objects using operators such as | (or), as (alias), and _ (wildcard). If the pattern matches the expression, the statements following the : are executed. The statements can be any valid Python code, such as print, return, break, etc.
  • The other keyword is used to specify a default case that is executed if none of the other patterns match. It is equivalent to using _ as a pattern

The most basic example:

x = 1 + 1

match x:
    case 1:
        print("x is 1")
    case 2:
        print("x is 2")
    case other:
        print("No match found")

Output:

x is 2

More Advanced Examples

Matching multiple values in one case

This example uses the | operator to match multiple values in one case clause:

user = input("Write your username: ")
match user:
    case "A" | "B" | "C":
        print("You are not allowed to access the database!")
    case "Boss":
        print("You are allowed to access the database!")
    case other:
        print("You are not a company member, you are not allowed to access the code!")

Output (may vary):

Write your username: A
You are not allowed to access the database!

Binding a variable to the matched value

This example demonstrates how to use the as operator to bind a variable to the matched value:

command = input("Enter a command: ")
match command.split():
    case ["go", direction] as result:
        print(f"You chose to go {direction}.")
    case ["look"]:
        print("You look around.")
    case other:
        print(f"Invalid command: {command}")

Output (depends on your input):

Enter a command: go foward 
You chose to go foward.

Using match/case within a function

Here is an example that uses the match/case statement to check the types of something being passed in:

def print_type(value):
    match value:
        case int():
            print("It's an integer.")
        case str():
            print("It's a string.")
        case list():
            print("It's a list.")
        case dict() as d:
            print(f"It's a dictionary with {len(d)} keys.")
        case _:
            print("I don't know what it is.")

# try the function
print_type(1)
# It's an integer.

print_type("Sling Academy!")
# It's a string.

print_type([1, 2, 3])
# It's a list.

print_type({"a": 1, "b": 2})
# It's a dictionary with 2 keys.

print_type(1.0)
# I don't know what it is.

This print_type() function takes a value as an argument and uses the match/case statement to compare it to different types using the () operator. If the value is an instance of a type, the corresponding case is executed. The as operator is used to bind a variable to the matched value, which can be used inside the case block. The _ operator is used as a wildcard to handle any other value.