Python Match-Case Statement

Python match statement began in Python 3.10 and offers user experience, good readability, and cleanliness in the code. The pattern matching technique in Python 3.10 is known as match-case.

This works similarly to the case construct. Read this article to learn more about Python Match-Case Statements.

What is a Python match-case Statement?

The conditional statement is referred to as the Switch Case. Further, the match case is the switch case of Python and was brought in Python 3.10.

Therefore, the first pattern that is matched will be run. This also allows to extraction of components.

Syntax

match variable_name:
   case 'pattern 1' : statement 1
   case 'pattern 2' : statement 2
   ...
   case 'pattern n' : statement n

Example

The code that is provided below, consists of a function known as a weekday. Further, it will receive an integer argument, then it needs to be matched with all the possible weekday number values and then return with the corresponding name of the day.


def weekday_action(day):
    match day:
        case "Monday":
            print("It's the beginning of the week.")
        case "Tuesday":
            print("It's still early in the week.")
        case "Wednesday":
            print("It's the middle of the week.")
        case "Thursday":
            print("It's almost Friday.")
        case "Friday":
            print("It's the end of the workweek. TGIF!")
        case "Saturday":
            print("It's the weekend!")
        case "Sunday":
            print("It's the weekend, but it's almost over.")
        case _:
            print("Invalid day entered.")

# Example usage:
weekday_action("Wednesday")
weekday_action("Sunday")
weekday_action("InvalidDay")

Output

# Example usage:
weekday_action("Wednesday")
weekday_action("Sunday")
weekday_action("InvalidDay")

Combined Cases in Python

It is possible to combine cases with the OR Operator and will be represented by the “|” symbol.

# Example cases
case_1 = True
case_2 = False
case_3 = True

# Combine cases using the OR operator (|)
result = case_1 | case_2 | case_3

# Display the result
print("Combined result:", result)

Output

Combined result: True

List as the Argument in Python

Python will match the expression against any literal and use the list as a case value. Hence, it can divide the variable number of items in the list into the sequence with the ‘*’ operator.

def greeting(details):
   match details:
      case [time, name]:
         return f'Good {time} {name}!'
      case [time, *names]:
         msg=''
         for name in names:
            msg+=f'Good {time} {name}!\n'
         return msg

print (greeting(["Evening", "John"]))
print (greeting(["Morning","Guest"]))
print (greeting(["Afternoon", "Albert", "Nick", "Rohan"]))

Output

Good Evening John!
Good Morning Guest!
Good Afternoon Albert!
Good Afternoon Nick!
Good Afternoon Rohan!

Use of “if” in “Case” Clause in Python

In Python, there’s a feature called match that helps us check different cases based on a value. Suppose, let’s assume it is a set of instructions for the computer to follow depending on what value we give it.

Example

Let us look at the example of the Use of “if” in a case clause in Python given below:

def process_data(value):
    match value:
        case 1:
            print("Processing data for case 1")
        case 2 if value > 0:
            print("Processing data for case 2 with a positive value")
        case 2:
            print("Processing data for case 2 with a non-positive value")
        case _:
            print("Processing data for other cases")

# Example usage
process_data(1)
process_data(2)
process_data(-1)

Output

Processing data for case 1
Processing data for case 2 with a positive value
Processing data for case 2 with a non-positive value
Processing data for other cases

Conclusion

Python match case will provide the instruction to a computer according to the different situations. Therefore, the student can improve their knowledge and will be able to understand the topics clearly through the examples provided in the article.

Python Match-Case Statement-FAQs

Q1. What is a match case statement in Python?

Ans. It is referred to as Pattern Matching and this feature was put in Python 3.10.

Q2. What is match () in Python?

Ans. The match function will analyze the string that needs to be matched for the required pattern in the RegEx Regular Expression, then will give the output as the first occurrence of such pattern match.

Q3. How does match case compare values in Python?

Ans. The match statement will enable you to run the pattern matching on values.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

Leave a Comment