Match Case Statements In Python. Topic 12


Introduction of Match Case Statements:

Python 3.10 version introduces new features, that is “match case statements”. It enhances the capabilities of the existing match statements. This feature is inspired by pattern-matching constructs in other programming languages and helps in expressing code and making it more readable.

About Match Statements:

Match statement in Python programming language is a powerful tool that helps us to match the structural pattern. You can match values against a set of patterns using this, and execute code corresponding to the first matching pattern. Using match statements we can write more complex and hierarchical code.


match value:
    case pattern1:
        # code to execute if value matches pattern1
    case pattern2:
        # code to execute if value matches pattern2
    case _:
        # default code to execute if no patterns match


from typing import Match

def match_example(value: int) -> str:
    match value:
        case 1:
            return "One"
        case 2 | 3:
            return "Two or Three"
        case 4:
            return "Four"
        case _:
            return "Other"

result = match_example(2)

In this example, the match_example function uses the match statement to check the value of input against different patterns. If the input is 1, then return “One”. If input is 2 or 3 then two and three will return. If no existing pattern is not matched “Other” will be returned.

Match case statements add more flexibility to the match statement by allowing multiple patterns to be associated with a single block of code. This makes the code more concise and readable, especially when dealing with complex data structures.

The Output Of This Code Will Be:

Two or Three

If you don’t know “If Else Conditional Statements in Python.” just click on read more.

I hope you understand Match Case Statements In Python. If you do not understand this topic just comment below with your email ID, and I will mail back to you.

Finite number of  lines code and infinite possibilities

Programmer, Arpan Bera

Leave a Reply

Your email address will not be published. Required fields are marked *

Arpan Bera

Coding is like Love – everyone can start, but only a few finish without errors

Keep Updated to our News and Blog