Basics

Python Match Case

Structural Pattern Matching

Python match-case enables pattern matching, introduced in Python 3.10.

Introduction to Match-Case in Python

The match-case statement in Python is a powerful tool introduced in Python 3.10 that facilitates pattern matching. It provides a more expressive and readable way to dispatch control based on the structure and contents of data, similar to switch-case statements found in other languages.

Unlike traditional if-else statements, match-case allows you to match patterns rather than simple values. This can make your code cleaner and more intuitive, especially when dealing with complex data structures.

Basic Syntax of Match-Case

The basic syntax of the match-case statement is as follows:

Here, subject is the value you want to match against various patterns. The underscore (_) acts as a wildcard pattern, matching anything if no other patterns do.

Example: Simple Match-Case Usage

Let's see a simple example where we use match-case to print different messages based on the value of a variable:

In this example, the check_status function uses match-case to print a message corresponding to the HTTP status code. If the code is not 200, 404, or 500, it defaults to printing "Unknown Code".

Advanced Pattern Matching

Pattern matching with match-case can become more sophisticated when dealing with complex data structures, like tuples, lists, or dictionaries. Let's look at an example that matches a tuple:

In this example, the match_point function matches a tuple representing a point in a 2D plane. It identifies whether the point lies on the origin, x-axis, y-axis, or elsewhere.

Conclusion

The match-case statement in Python is a versatile and expressive way to handle complex control flows based on data patterns. It can greatly enhance the readability and maintainability of your code, especially in scenarios involving structured data.

With this understanding, you can start incorporating match-case into your Python projects to simplify your code logic and improve clarity.

Previous
If Else