Skip to main content

What is Match Case?

Introduced in Python 3.10, the match statement (also called structural pattern matching) is a clean and readable alternative to writing long chains of if-elif-else statements. Think of it like checking a variable against a list of possible matches.

Basic Syntax

Here is how you write a basic match statement to check response status codes:

How it works:

  1. Python takes the value of status_code and checks it against each case.
  2. As soon as it finds a match, it runs the code under that case block.
  3. The wildcard case _: acts as a default fallback (similar to else). It matches anything if no previous cases matched.
Unlike some other programming languages (like Java or C++ switch statements), Python’s match statement does not fall through. Once a match is found, only that block runs, and Python exits the match block. You don’t need break statements!

Combining Patterns (| OR)

You can check if a variable matches one of multiple values in a single case block by separating them with the | (OR) symbol:

Conditional Guards (if in case)

Sometimes you want to match a pattern only if a certain condition is also met. You can add an if condition (called a guard) to a case:
In this example, n acts as a temporary variable name that captures the value of number so it can be evaluated in the if guard.

Common mistakes

The wildcard case case _: matches everything. If you place it before other cases, it will always match, and the cases below it will never run! Python will raise a SyntaxError if you place it anywhere except as the last case.
You cannot use comparison operators directly in case patterns like case < 10:. You must use a guard pattern: case n if n < 10:.

Practice & Exercises

To reinforce what you’ve learned in this section (Match Case pattern matching), practice with these interactive notebooks:

Follow-Along Practice

Practice match-case basic structures, combining patterns, and using conditional guards.💻 VS Code | 🚀 Colab | 📥 Download

Practice Exercises

Test your knowledge with hands-on exercises on status code matching, day patterns, and number range guards.💻 VS Code | 🚀 Colab | 📥 Download

What’s next?

Now let’s learn about loops to repeat code efficiently!

Loops

Repeat code without copying