Content · Programming · Python

Python match Statements: Pattern Matching Basics

Use match to choose a branch based on the structure or value of one subject.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Use match to choose a branch based on the structure or value of one subject.

What You Will Learn


A match statement compares one subject against case patterns in order and executes the first matching case. Literal patterns match exact values, while a bare name such as case value captures anything and is not a constant comparison. A final case _ works as a catch-all. Use if/elif when you only need a few ordinary Boolean tests.

A match statement is particularly valuable for messages with different shapes, not just integers.

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

def describe_status(status):
    match status:
        case 200:
            return "Request succeeded"
        case 404:
            return "Resource not found"
        case _:
            return "Other status"

for value in (200, 404, 503):
    print(value, describe_status(value))

How the Example Works


  • The function describe_status defines reusable behavior; its body executes when it is called, not when it is declared.
  • The loop demonstrates when each value is processed or when cleanup and exception handling take effect.
  • The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.

Expected output from the example:

200 Request succeeded
404 Resource not found
503 Other status

When You Would Use This


Pattern matching can simplify dispatching application commands or decoding structured messages from a trusted parser. It chooses a branch based on shape and selected values, but application-level validation is still necessary. Compare it with an if/elif chain if the problem only involves simple Boolean expressions.

Practice: Modify the Code


Add a branch for 401 and check that all other statuses still reach the wildcard.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Writing case ERROR expecting to compare an existing variable, when a bare name is actually a capture pattern.
  • Assuming all cases run instead of only the first matching branch.

Key Takeaways


  • Use match to choose a branch based on the structure or value of one subject.
  • A match statement compares one subject against case patterns in order and executes the first matching case.
  • A match statement is particularly valuable for messages with different shapes, not just integers.
Share this resourceSend this page to someone who may find it useful.