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

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots