Python Match ( Switch ) Case


Yes, I didn’t know that python has switch case. Since first time I switched from php to python in 20202, I started with python 3.6 and 3.7 and there were no switch case, insteadh there were a lot of nested if else.

Python 3.10 introduced a new feature called match statement, which is similar to the switch case in other programming languages. This feature allows for more readable and concise code when dealing with multiple conditions.

Basic Syntax

The basic syntax of the match statement is as follows:

def http_status(status):
    match status:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case 500:
            return "Internal Server Error"
        case _:
            return "Unknown Status"

# Example usage
print(http_status(200))  # Output: OK
print(http_status(404))  # Output: Not Found
print(http_status(500))  # Output: Internal Server Error
print(http_status(123))  # Output: Unknown Status

Using Patterns

The match statement can also work with patterns, making it more powerful. Here is an example:

def process_point(point):
    match point:
        case (0, 0):
            return "Origin"
        case (x, 0):
            return f"X={x} on the X-axis"
        case (0, y):
            return f"Y={y} on the Y-axis"
        case (x, y):
            return f"Point at X={x}, Y={y}"
        case _:
            return "Unknown point"

In this example, the match statement matches the point variable against different patterns and executes the corresponding block of code.

Guard Clauses

You can also use guard clauses with the match statement to add additional conditions:

def check_number(num):
    match num:
        case x if x < 0:
            return "Negative number"
        case x if x == 0:
            return "Zero"
        case x if x > 0:
            return "Positive number"

In this example, the match statement uses guard clauses to check additional conditions for each case.

Example using regex

def validate_username(username: str) -> str:
    """
    Validate usernames based on different patterns:
    - Standard: Letters and numbers only (e.g., "john123")
    - Gamer: Ends with numbers (e.g., "ninja42")
    - Professional: Contains dots or underscores (e.g., "john.doe")
    """
    match username.lower():
        # Professional username with dots or underscores
        case name if re.match(r'^[a-z][a-z._]{2,}[a-z]$', name):
            return f"✅ Professional username: {username}"
        
        # Gamer tag ending with numbers
        case name if re.match(r'^[a-z]+\d+$', name):
            return f"🎮 Gamer username: {username}"
            
        # Standard alphanumeric username
        case name if re.match(r'^[a-z][a-z0-9]{2,}$', name):
            return f"📝 Standard username: {username}"
            
        case _:
            return f"❌ Invalid username: {username}"

# Example usage
usernames = [
    "john.doe",     # Professional
    "ninja42",      # Gamer
    "alice123",     # Standard
    "bob_smith",    # Professional
    "user@123",     # Invalid
]

# Test all usernames
for username in usernames:
    result = validate_username(username)
    print(result)

Output

# Output:
 Professional username: john.doe
🎮 Gamer username: ninja42
📝 Standard username: alice123
 Professional username: bob_smith
 Invalid username: user@123

Conclusion

The match statement in Python is a powerful feature that can make your code more readable and concise. It allows you to match values and patterns, and use guard clauses for additional conditions. This feature is especially useful when dealing with multiple conditions and complex data structures.