Match Statement

  • The Python Match Statement allows developers to compare a value against multiple patterns using match and case, making conditional logic more structured and readable than traditional if-elif statements.
  • The match statement in Python is used to compare a value against multiple patterns, similar to a switch-case statement in other programming languages.

    It was introduced in Python 3.10 and is also called Structural Pattern Matching.

    Instead of writing many if-elif-else conditions, we use match to make code:

    • Cleaner

    • Easier to read

    • More organized

    Syntax

    match variable:

        case pattern1:

            # code block

        case pattern2:

            # code block

        case _:

            # default case


    match → checks the value
    case → compares patterns
    _ → works like default

Basic Match Example

This program checks a number and prints the day of the week.

day = 3

match day:
    case 1:
        print("Monday")
    case 2:
        print("Tuesday")
    case 3:
        print("Wednesday")
    case _:
        print("Invalid day")

Match with String

This example checks a fruit name and prints its color.

fruit = "apple"

match fruit:
    case "banana":
        print("Yellow")
    case "apple":
        print("Red")
    case "grape":
        print("Purple")
    case _:
        print("Unknown fruit")

Multiple Patterns in One Case

This program checks if a character is a vowel.

char = "a"

match char:
    case "a" | "e" | "i" | "o" | "u":
        print("Vowel")
    case _:
        print("Consonant")