Python Mastery โ€“ From Basics to Brilliance / Control Flow & Decision Making

Match Case Statements

๐Ÿ”€ Match-Case Statements

The match-case statement is used to compare a value against different patterns.

It is similar to switch-case in some other programming languages.

Basic Syntax

match value:
    case pattern1:
        # code
    case pattern2:
        # code
    case _:
        # default code

๐ŸŸข Basic Example

day = 2

match day:
    case 1:
        print("Monday")
    case 2:
        print("Tuesday") #This match will be executed
    case 3:
        print("Wednesday")
    case _:
        print("Invalid day")

Python checks each case until it finds a match.


๐Ÿ”น Default Case _

The _ acts as the default case.

choice = 5

match choice:
    case 1:
        print("Start")
    case 2:
        print("Exit")
    case _:
        print("Invalid choice") #This match will be executed

๐Ÿ”น Multiple Values in One Case

You can match multiple values using |.

day = "Saturday"

match day:
    case "Saturday" | "Sunday":
        print("Weekend") #This block will be executed
    case _:
        print("Weekday")

๐Ÿ”น match-case vs if-elif-else

The same logic can be written using if-elif:

day = 2

if day == 1:
    print("Monday")
elif day == 2:
    print("Tuesday")
else:
    print("Invalid")

Using match-case:

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

Note: match-case was introduced in Python 3.10 and is especially useful when you have many possible patterns to match.