Sling Academy
Home/Python/Python match/case statement (with examples)

Python match/case statement (with examples)

Last updated: July 18, 2023

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.

Next Article: Python: Return Multiple Results from a Function (3 Ways)

Previous Article: Making use of the “with” statement in Python (4 examples)

Series: Control Flow & Functions in Python

Python

Related Articles

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types