engineering

Python Switch Statements: Examples and Use Cases

Python Switch Statements: Examples and Use Cases

Python 3.10 introduced the match statement, providing an elegant way to implement switch-case functionality. This article explores its syntax along with examples and various use cases

Yogini Bende

Yogini Bende

Sep 17, 2024 3 min read

Prior to Python 3.10, developers had to rely on if-elif-else chains or dictionary mappings to implement switch-case-like behavior. The introduction of the match statement offers a more readable and powerful alternative.

You can also read more in-depth about Python Features before jumping on this topic.

Let's understand how you can use a match keyword and implement switch statement in Python.

Basic Syntax

The basic syntax of a match statement in Python is as follows:

match variable:
    case pattern1:
        # Code for pattern1
    case pattern2:
        # Code for pattern2
    case _:
        # Default case

One important thing to note here is, the underscore symbol used in the last case is used to define a default case for switch statement in Python.

This can be used for multiple use-cases. Let's now understand some examples and use cases of switch in python

Use Cases and Examples

1. Simple Value Matching

The most straightforward use of match is to compare a variable against specific values. Consider you have to match a status with different codes and add a response accordingly. You can use switch case in following way:

def check_status(status):
    match status:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case _:
            return "Unknown Status"

print(check_status(200))  # Output: OK
print(check_status(404))  # Output: Not Found
print(check_status(500))  # Output: Unknown Status

2. Pattern Matching with Data Structures

Suppose you are parsing some data and you have to understand and differenciate between different data structure, switch statement will be very handy this time. match can be used to destructure and match complex data structures:

def process_data(data):
    match data:
        case [x, y]:
            return f"Coordinates: ({x}, {y})"
        case {"name": name, "age": age}:
            return f"{name} is {age} years old"
        case str():
            return f"Received a string: {data}"
        case _:
            return "Unrecognized data format"

print(process_data([10, 20]))          # Output: Coordinates: (10, 20)
print(process_data({"name": "Alice", "age": 30}))  # Output: Alice is 30 years old
print(process_data("Hello"))           # Output: Received a string: Hello
print(process_data(42))                # Output: Unrecognized data format

3. Combining Patterns

If there are multiple cases and same result have to apply to all of those, you can combine that and execute your switch state,emt. Multiple patterns can be combined using the | operator:

def classify_number(num):
    match num:
        case 0 | 1 | 2:
            return "Small number"
        case x if x < 0:
            return "Negative number"
        case x if x % 2 == 0:
            return "Even number"
        case _:
            return "Odd number"

print(classify_number(1))    # Output: Small number
print(classify_number(-5))   # Output: Negative number
print(classify_number(10))   # Output: Even number
print(classify_number(7))    # Output: Odd number

4. Object Pattern Matching

Not only for the simple string and condition matching, you can use switch and match to handle some complex pattern matching. match can be used with custom classes and their attributes:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def classify_point(point):
    match point:
        case Point(x=0, y=0):
            return "Origin"
        case Point(x=0, y=y):
            return f"On Y-axis at y={y}"
        case Point(x=x, y=0):
            return f"On X-axis at x={x}"
        case Point():
            return f"Point at ({point.x}, {point.y})"
        case _:
            return "Not a point"

print(classify_point(Point(0, 0)))  # Output: Origin
print(classify_point(Point(0, 5)))  # Output: On Y-axis at y=5
print(classify_point(Point(3, 0)))  # Output: On X-axis at x=3
print(classify_point(Point(2, 3)))  # Output: Point at (2, 3)
print(classify_point("Not a point"))  # Output: Not a point

Conclusion

The match statement in Python 3.10+ provides a powerful and flexible way to implement switch-case functionality. It offers clear syntax for simple value matching, pattern matching with complex data structures, and even object-oriented pattern matching. By leveraging these capabilities, developers can write more readable and maintainable code for various scenarios.

If you are looking for a Python developer jobs, you are at a right place. Check out Peerlist Jobs to find many remote jobs for python developers and apply them with your Peerlist Profile.

Join Peerlist

or continue with email

By clicking "Join Peerlist“ you agree to our Code of Conduct, Terms of Service and Privacy Policy.