Python match case Statement

This article is a complementary resource to the Learn Python Basics course.

Python match case Statement

The match...case evaluates a given expression, and based on the evaluated value, it executes certain associated statement(s).

fruit = "grapes"

match fruit:
    case "banana":
        print("It's a banana!")
    case "orange":
        print("It's an orange!")
    case "apple":
        print("It's an apple!")
    case other:
        print("Unknown fruit")

# Output: Unknown fruit

Here, the value of fruit doesn't match with any of the cases. So the statement inside case other: is executed, printing "Unknown fruit."


Syntax of match...case

The basic syntax of the match...case statement in Python is:

match expression:
    case value1:
        # statements

    case value2:
        # statements

    ...

    case other:
        # default statements

Here,

  • If the value of the expression matches any of the specified values (e.g., value1, value2, etc.), the corresponding statements for the matching case are executed.
  • If no match is found, the default case (case other) is executed.

Note: You can use _ instead of other as a default case as:

case _:
  print("Unknown")

Python match...case Flowchart

Python match...case Statement
Working of match...case in Python

Example: Basic match...case

number = 48

match number:
    case 29:
        print('Small')
    case 42:
        print('Medium')
    case 44:
        print('Large')
    case 48:
        print('Extra Large')
    case other:
        print('Unknown')

# Output: Extra Large

Here, the value of number matches case 48:, so the associated code is executed.


Using Tuples in match...case

Python match...case allows tuples in cases, enabling structured pattern matching.

Let's look at an example.

plot = (0, 4)

match plot:
    case (4, 0):
        print('on x-axis')
    case (0, 4):
        print('on y-axis')
    case (0, 0):
        print('center')

# Output: on y-axis

Here, the tuple plot is compared with each case. Since it matches case (0, 4):, the associated statement is executed.