Sunday, May 17, 2026

Python Material - Part - 14 - match

 """The match statement in Python (introduced in Python 3.10) is a structural pattern matching feature.

It allows you to compare a variable against a series of patterns and execute code based on which pattern matches
— similar to a switch statement in other languages (C language), but more powerful."""
"""
🔄 Basic Syntax

match variable:
case pattern1:
# code block
case pattern2:
# code block
case _:
# default case

"""

"""Real-Time Example: API Response Status Handling
Imagine you're writing a backend service that receives a response from an external API.
Based on the response status, you want to handle different scenarios."""
def handle_api_response(response):
match response:
case {"status": 200, "data": data}:
print(" Success! Processing data...", end="")
print(f"Data: {data}")
case {"status": 404}:
print(" Error: Resource not found.")
case {"status": 500}:
print("🚨 Server error. Try again later.")
case _:
print("🔍 Unexpected response format.")


# Sample API responses

response1 = {"status": 404}
response2 = {"status": 500}
response3 = {"status": 200, "data": {"user": "John", "id": 123}}
response4 = {"Error code": 1003}

# handle_api_response(response1) # Output: Error: Resource not found.
# handle_api_response(response2) # Output: 🚨 Server error. Try again later.
# handle_api_response(response3) # Output: Success! Processing data...Data: {'user': 'John', 'id': 123}
# handle_api_response(response4) # Output: 🔍 Unexpected response format.


"""
Explanation:
match response: tells Python you're going to match the response dictionary against multiple patterns.

Each case checks if the dictionary structure fits the pattern:

{"status": 200, "data": data} captures the data field into a variable.

{"status": 404} matches if the status is 404.

_ acts like else — a fallback when no other patterns match.
"""

Author: Boyina Narendra

Supporting Author: M. Meera Sindhu

Request: If you find this information useful, please provide your valuable comments

No comments:

Post a Comment