Match Statement - Python

Python Match Statement

Python 3.10 introduced a new feature called match-case statement, which is similar to the switch statement in other programming languages like C, Java, or JavaScript. It provides a powerful and more readable way to handle multiple conditions using pattern matching.


✅ What is Python Match Statement?

The match statement in Python is a control flow structure that allows you to compare a value against one or more patterns and execute code based on the first matching pattern. It is Python’s modern alternative to long chains of if-elif-else.


📌 Uses of Match Statement

  • Replacing long if-elif-else conditions with cleaner syntax.
  • Handling multiple constant values more effectively.
  • Pattern matching with complex data structures like lists, tuples, and dictionaries.
  • Improving code readability and maintainability.

✨ Characteristics of Match Statement

  • Introduced in Python 3.10.
  • Similar to switch-case but more powerful due to pattern matching.
  • Supports default values with case _:.
  • Can use guards (if conditions) for advanced checks.
  • Stops execution once a matching case is found.

⚙️ How Does Match Statement Work?

The match statement compares the input expression with different cases. When a match is found, the corresponding block of code executes. If no match is found, the default case (_) executes.


📝 Syntax of Match Statement


match variable:
    case value1:
        # code for value1
    case value2:
        # code for value2
    case _:
        # default case


💡 Example of Python Match


def check_day(day):
    match day:
        case "Mon":
            return "Start of the work week!"
        case "Fri":
            return "Almost weekend!"
        case "Sat" | "Sun":  # Combine values
            return "Weekend fun!"
        case _:
            return "Midweek day."

print(check_day("Mon"))
print(check_day("Sun"))
print(check_day("Wed"))

Output:

Start of the work week!
Weekend fun!
Midweek day.

🔹 Default Value in Match

The default case in Python match is written using an underscore (case _:). It runs when no other case matches.


number = 7
match number:
    case 1:
        print("One")
    case 2:
        print("Two")
    case _:
        print("Unknown number")

Output: Unknown number


🔗 Combine Values in Match

You can combine multiple values in one case using | (bitwise OR operator).


status = 200
match status:
    case 200 | 201:
        print("Success")
    case 400 | 404:
        print("Client Error")
    case 500 | 503:
        print("Server Error")
    case _:
        print("Unknown Status")

Output: Success


🛡️ If Statements as Guards

Guards let you add extra conditions inside a case using if.


x = 15
match x:
    case n if n < 10:
        print("Less than 10")
    case n if n < 20:
        print("Between 10 and 19")
    case _:
        print("20 or more")

Output: Between 10 and 19


✍️ Exercises for Practice

  1. Write a program using match to check if a number is even, odd, or zero.
  2. Create a match case program to print different greetings for each day of the week.
  3. Use guards to check if a number is positive, negative, or zero.
  4. Build a match case system that categorizes HTTP status codes (1xx, 2xx, 3xx, 4xx, 5xx).

❓ Frequently Asked Questions (FAQ)

Q1. Is match available in all versions of Python?
No, it was introduced in Python 3.10. Older versions do not support it.
Q2. Is match the same as switch-case?
Yes, it is Python’s version of switch-case but more powerful with pattern matching and guards.
Q3. Can I use variables in match cases?
Yes, match supports variables, combined values, and even destructuring.
Q4. What does case _: mean?
It acts as the default case, similar to else in if-else.

📌 Final Thoughts

The match statement in Python makes code cleaner, more readable, and easier to maintain compared to long chains of if-elif-else. Whether you are categorizing data, handling user input, or building a decision system, match is a great tool to simplify your Python programs.


 Related Python Tutorials


👉 Continue Learning: Explore more beginner-friendly topics and practice materials in our Programming Resource Hub.

Post a Comment

0 Comments