What is Match Case Statement in Python?

Deepsandhya Shukla 05 Feb, 2024 • 5 min read

Introduction

The match case statement in Python is a powerful feature that allows us to perform pattern matching and make decisions based on the values of variables. It provides a concise, readable way to handle multiple conditions and execute specific code blocks accordingly. In this article, we will explore Python’s syntax, usage, benefits, and examples of match case statements. We will also compare it with other conditional statements, discuss common mistakes and best practices, and highlight its limitations and compatibility.

What is a Match Case Statement?

A match case statement is a conditional statement that matches the value of an expression against a set of patterns and executes the code block associated with the first matching pattern. It is similar to the switch-case statement in other programming languages. The match case statement was introduced in Python 3.10 as a new feature to simplify conditional branching and improve code readability.

Want to learn python without spending money? Here’s a FREE course on introduction to python to make your dream come true!

Syntax and Usage

The syntax of the match case statement in Python is as follows:

match expression:
    case pattern1:
        # code block for pattern1
    case pattern2:
        # code block for pattern2
    ...
    case patternN:
        # code block for patternN
    case _:
        # default code block

The match keyword is followed by the expression that we want to match. A pattern and a colon follow each case keyword. The code block associated with each pattern is indented below the case statement. We can have multiple case statements and a default case denoted by an underscore (_).

Benefits of Using Match Case Statements

Using match case statements in Python offers several benefits:

  • Improved Readability: Match case statements are more concise and readable to handle multiple conditions than nested if-else statements.
  • Pattern Matching: Match case statements allow us to match values against patterns, making it easier to handle complex conditions and perform specific actions based on the matched pattern.
  • Code Organization: By using match case statements, we can organize our code into separate code blocks for each pattern, making it more modular and maintainable.
  • Error Prevention: Match case statements help prevent errors by explicitly handling all possible cases. This reduces the chances of overlooking a specific condition.

Examples of Match Case Statements in Python

Let’s explore some examples to understand how match case statements work in Python.

Matching Values with Exact Matches

def check_grade(grade):
    match grade:
        case "A":
            print("Excellent!")
        case "B":
            print("Good!")
        case "C":
            print("Average!")
        case _:
            print("Invalid grade!")

check_grade("A")  # Output: Excellent!
check_grade("B")  # Output: Good!
check_grade("D")  # Output: Invalid grade!

In this example, we define a function check_grade that takes a grade as input. The match case statement matches the grade value against different patterns and executes the corresponding code block.

Matching Values with Patterns

def check_number(num):
    match num:
        case 0:
            print("Zero")
        case n if n > 0:
            print("Positive")
        case n if n < 0:
            print("Negative")

check_number(0)   # Output: Zero
check_number(10)  # Output: Positive
check_number(-5)  # Output: Negative

In this example, we define a function check_number that takes a number as input. The match case statement matches the value of the number against different patterns, including a pattern with a condition.

Also Read: A Comprehensive Guide To Conditional Statements in Python For Data Science Beginners

Matching Multiple Conditions

def check_age(age):
    match age:
        case n if n < 18:
            print("Minor")
        case n if 18 <= n < 65:
            print("Adult")
        case n if n >= 65:
            print("Senior")

check_age(15)  # Output: Minor
check_age(30)  # Output: Adult
check_age(70)  # Output: Senior

In this example, we define a function check_age that takes an age as input. The match case statement matches the age value against different patterns, including patterns with multiple conditions.

Using Match Case with Functions and Methods

def process_data(data):
    match data:
        case []:
            print("Empty data")
        case [x]:
            print(f"Single element: {x}")
        case [x, y]:
            print(f"Two elements: {x}, {y}")
        case _:
            print("Multiple elements")

process_data([])          # Output: Empty data
process_data([10])        # Output: Single element: 10
process_data([10, 20])    # Output: Two elements: 10, 20
process_data([10, 20, 30])  # Output: Multiple elements

In this example, we define a function process_data that takes a list as input. The match case statement matches the list’s value against different patterns, including patterns with multiple elements.

Comparison with Other Conditional Statements in Python

If-Else Statements

If-else statements are a common way to handle conditional branching in Python. However, match case statements offer a more concise and readable alternative, especially when dealing with multiple conditions.

grade = "A"

if grade == "A":
    print("Excellent!")
elif grade == "B":
    print("Good!")
elif grade == "C":
    print("Average!")
else:
    print("Invalid grade!")

The above code can be rewritten using a match case statement as shown in Example 4.1.

Nested If-Else Statements

Nested if-else statements are used when we have multiple levels of conditions. While they can handle complex conditions, they often result in harder to read and maintain code.

age = 30

if age < 18:
    print("Minor")
else:
    if 18 <= age < 65:
        print("Adult")
    else:
        print("Senior")

The above code can be rewritten using a match case statement as shown in example above.

Common Mistakes and Pitfalls with Match Case Statements

Forgetting to Include a Default Case

One common mistake when using match case statements is forgetting to include a default case. If none of the patterns match the value of the expression, an error will occur. To avoid this, always include a default case denoted by an underscore (_).

Incorrect Syntax or Indentation

Another common mistake is incorrect syntax or indentation. Make sure to follow the correct syntax and indent the code blocks properly. Improper indentation can lead to syntax errors or unexpected behavior.

Misunderstanding Pattern Matching

Understanding pattern matching is crucial when using match case statements. Familiarize yourself with the different patterns and their usage. Incorrect patterns may result in unexpected behavior or errors.

Limitations and Compatibility of Match Case in Python

Python Versions Supporting Match Case

The match case statement was introduced in Python 3.10. Therefore, it is only available in Python versions 3.10 and later. If you are using an older version of Python, you must upgrade to utilize this feature.

Compatibility with Other Python Libraries and Frameworks

Match case statements are compatible with other Python libraries and frameworks. However, it is important to ensure that the libraries and frameworks you are using are compatible with the version of Python that supports match case.

Conclusion

The match case statement in Python provides a powerful and concise way to handle multiple conditions and perform pattern matching. It improves code readability, organization, and error prevention. By understanding the syntax, usage, benefits, and examples of match case statements, you can leverage this feature to write cleaner and more efficient code. Remember to follow best practices, test thoroughly, and be aware of the limitations and compatibility of match case in Python.

Want to learn python for free? Enroll today in our FREE introduction to python program!

Frequently Asked Questions

Q1. What is the match case value in Python?

A. Match case in Python is a feature for pattern matching, allowing precise conditions and decisions based on variable values.

Q2. What does match() do in Python?

A. In Python, match() is a method associated with pattern matching, enabling structured comparison of values and execution of corresponding code blocks.

Q3. What is match case in Python simple program?

A. Match case in a simple Python program involves using the match statement to handle various conditions based on specific variable values, enhancing code readability.

Q4. What is match in Python with example?

A. In Python, ‘match’ is a keyword used for pattern matching. An example includes using match case to elegantly handle multiple conditions and execute appropriate code blocks.

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers

Clear

Related Courses

image.name
0 Hrs 70 Lessons
5

Introduction to Python

Free