Open In App

Python Match Case Statement

Last Updated : 14 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Developers coming from languages like C/C++ or Java know that there is a conditional statement known as a Switch Case. This Match Case is the Switch Case of Python which was introduced in Python 3.10. Here we have to first pass a parameter and then try to check with which case the parameter is getting satisfied. If we find a match we will execute some code and if there is no match at all, a default action will take place.

Python Match Case Statement Syntax

The match case statement in Python is initialized with the match keyword followed by the parameter to be matched. Then various cases are defined using the case keyword and the pattern to match the parameter. The “_” is the wildcard character that runs when all the cases fail to match the parameter value.

match parameter:
    case pattern1:
        # code for pattern 1
    case pattern2:
        # code for pattern 2
    .
    .
    case patterN:
        # code for pattern N
    case _:
        # default code block

Now, let us see a few examples to know how the match case statement works in Python.

Simple Match Case Statement

In a simple Python match case statement, the exact value is compared and matched with the case pattern value. There are different test cases and their corresponding code which will execute only when a case is matched. Otherwise, there is a default case which executes when all the defined cases are not matched.

Example: In this example we will ask the user to enter a value between 1 and 3 and display its corresponding number in words using the simple match case statement.

Python
# simple match case statement
def runMatch():
    num = int(input("Enter a number between 1 and 3: "))
    
    # match case
    match num:
        # pattern 1
        case 1:
            print("One")
        # pattern 2
        case 2:
            print("Two")
        # pattern 3
        case 3:
            print("Three")
        # default pattern
        case _:
            print("Number not between 1 and 3")
            
runMatch()

Output:

Enter a number between 1 and 3: 5
Number not between 1 and 3

Match Case Statement with OR Operator

Match case statement in Python are meant to be for only matching the patterns and specific keywords or parameters. But we can also use match case statement in python when there are more than one case that results in same output. In this case, we can use pipe operator, also known as OR Operator in match case statement.

Example: In this example we will ask the user to enter a value between 1 and 6. Then using the match case with OR operator we have clubbed the pairs one 1 case each which will display its corresponding number in words.

Python
# python match case with OR operator
def runMatch():
    num = int(input("Enter a number between 1 and 6: "))
    
    # match case
    match num:
        # pattern 1
        case 1 | 2:
            print("One or Two")
        # pattern 2
        case 3 | 4:
            print("Three or Four")
        # pattern 3
        case 5 | 6:
            print("Five or Six")
        # default pattern
        case _:
            print("Number not between 1 and 6")
            
runMatch()

Output:

Enter a number between 1 and 6: 4
Three or Four

Match Case Statement with Python If Condition

We also can use the Python If condition along with match case statement when instead of matching the exact value, we use a condition. Based on the condition, if the value is True and matches the case pattern, the code block is executed.

Example: In this example, we will use if condition along with match case statement to check if a number entered bt the user id positive, negative or zero.

Python
# python match case with if condition
def runMatch():
    num = int(input("Enter a number: "))
    
    # match case
    match num:
        # pattern 1
        case num if num > 0:
            print("Positive")
        # pattern 2
        case num if num < 0:
            print("Negative")
        # default pattern
        case _:
            print("Zero")
            
runMatch()

Output:

Enter a number: -15
Negative

Match Case with the Sequence Pattern

Python match case statements are commonly used to match sequence patterns such as lists and strings. It is quite easy and can use positional arguments for checking the the patterns.

Example: In this example, we are using a python string to check if a character is present in the string or not using match case. We provide the string along with the index of the character we want to check for in the string to the match case. Then we defined the match cases as to what that character might be.

Python
# match case to check a character in a string
def runMatch():
    myStr = "Hello World"
     
    # match case
    match (myStr[6]):
        case "w":
            print("Case 1 matches")
        case "W":
            print("Case 2 matches")
        case _:
            print("Character not in the string")
            
runMatch()

Output:

Case 2 matches

Example: In this example we are using a python list for pattern matching. We are matching the first element of the lost and also used positional arguments to match the rest of the list.

Python
# python match case with list
def runMatch(mystr):
    
    # match case
    match mystr:
        # pattern 1
        case ["a"]:
            print("a")
        # pattern 2
        case ["a", *b]:
            print(f"a and {b}")
        # pattern 3
        case [*a, "e"] | (*a, "e"):
            print(f"{a} and e")
        # default pattern
        case _:
            print("No data")
            
runMatch([])
runMatch(["a"])
runMatch(["a", "b"])
runMatch(["b", "c", "d", "e"])

Output:

No data
a
a and ['b']
['b', 'c', 'd'] and e 

Match Case Statement with Python Dictionary

Python match case statements can handle dictionary as well. It can match a single key or multiple keys. The keys and values must reside in the dictionary, if there is any misplaced value or any key which does not exist and does not match the actual dictionary and value, that case will be discarded.

Example: In this example, we are using dictionary with match case statement in python. We are providing dictionaries with different data to the match case, and it will match the dictionary keys with different cases provided.

Python
# match case with python dictionaryu
def runMatch(dictionary):
    # match case
    match dictionary:
        # pattern 1
        case {"name": n, "age": a}:
            print(f"Name:{n}, Age:{a}")
        # pattern 2
        case {"name": n, "salary": s}:
            print(f"Name:{n}, Salary:{s}")
        # default pattern
        case _ :
            print("Data does not exist")

runMatch({"name": "Jay", "age": 24})
runMatch({"name": "Ed", "salary": 25000})
runMatch({"name": "Al", "age": 27})
runMatch({})

Output:

Name:Jay, Age:24
Name:Ed, Salary:25000
Name:Al, Age:27
Data does not exist

Match Case Statement with Python Class

We can also use Python classes to match cases using the Python match case statements. This will make the code very much clean,  neat, and more importantly easily readable. It makes the use of the Python dataclasses module.

Example: In this example, we created two classes called Person and Programmer. The first thought after seeing the match statement would be that the Programmer and Person inside the match statement would create an instance of the respective classes, but it is not the case. It will check for the instance with the given values. So the case Programmer(“Om”, language = “Python”, framework = “Django”)  will not create an instance but will check that the object passed whose name is instance is a  real instance of the Programmer class, then it will check for the name that is  “Om”, language that is “Python” and then framework that is “Django”. This way we can check for the values in the instance of any class.

Python
# match case with python classes
# import dataclass module
from dataclasses import dataclass

#Class 1
@dataclass
class Person:
    name: str
    age: int
    salary: int

# class 2
@dataclass
class Programmer:
    name: str
    language: str
    framework: str

def runMatch(instance):
    # match case
    match instance:
        # pattern 1
        case Programmer("Om", language="Python", framework="Django"):
            print(f"Name: Om, Language:Python, Framework:Django")
        # pattern 2
        case Programmer("Rishabh", "C++"):
            print("Name:Rishabh, Language:C++")
        # pattern 3
        case Person("Vishal", age=5, salary=100):
            print("Name:Vishal")
        # pattern 4
        case Programmer(name, language, framework):
            print(f"Name:{name}, Language:{language}, Framework:{framework}")
        # pattern 5
        case Person():
            print("He is just a person !")
        # default case
        case _:
            print("This person is nothiing!")

programmer1 = Programmer("Om", "Python", "Django")
programmer2 = Programmer("Rishabh", "C++", None)
programmer3 = Programmer("Sankalp", "Javascript", "React")
person1 = Person("Vishal", 5, 100)
runMatch(programmer1)
runMatch(programmer2)
runMatch(person1)
runMatch(programmer3)

Output:

Name: Om, Language:Python, Framework:Django
Name:Rishabh, Language:C++
Name:Vishal
Name:Sankalp, Language:Javascript, Framework:React

Python Match Case Statement FAQ

Q: What is the match case statement in Python?

A: The match-case statement, also known as pattern matching, is a feature introduced in Python 3.10. It provides a concise and expressive way to perform pattern matching on data structures, such as tuples, lists, and classes. It allows you to match the value of an expression against a series of patterns and execute the corresponding block of code for the matched pattern.

Q: How does the match case statement differ from if-elif-else statements?

A: The match-case statement is a more powerful and expressive construct compared to if-elif-else statements. While if-elif-else statements rely on boolean expressions, match-case statements can match patterns based on the structure and value of the data. Match-case statements provide a more structured and readable way to handle multiple conditions and perform different actions based on those conditions.

Q: What are the benefits of using the match-case statement?

A: The match-case statement offers several benefits, including:

  • Conciseness: Match-case statements allow you to express complex branching logic in a concise and readable manner.
  • Readability: Pattern matching makes the code more readable and self-explanatory, as it closely resembles the problem domain.
  • Safety: Match-case statements provide exhaustive pattern matching, ensuring that all possible cases are handled.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads