Built with Tutify.io

    AIStudyLabs

    Replacement of switch statement in Python?

    Replacement of switch statement in Python?

    Are there any replacements of switch statements in Python? Switch statements allow you to handle multiple cases with concise and readable code. Python does not have a built-in switch statement, We can implement switch-like structures in our code, using different ways.

    In this article, we will learn these different approaches to implementing switch-like structures in Python, along with different examples.

    <a id="h-1-what-is-switch-statement"></a>

    1. What is Switch Statement?

    In Programming, a switch statement is a control flow statement that allows a program to perform different actions based on the value of a variable or expression.

    The switch statement evaluates the value of the variable or expression and then executes the appropriate block of code based on the value.

    Switch statements are often used in situations where a program needs to perform different actions based on a limited number of possible values.

    In programming, Switch statements provide a way to handle multiple cases in a concise and modular way. Instead of writing a series of if-else statements, a switch statement is more readable and easier to understand, when there are many cases to consider.

    Below is a pseudocode that illustrates the switch statement:

    
    # Switch statement example from other languages
    # This doesn't work in Python
    switch (expression) {
        case value1:
            # Execute when expression == value1
            break;
        case value2:
            # Execute  when expression == value2
            break;
        case value3:
            # Execute  when expression == value3
            break;
        default:
            # Execute  if expression doesn't match any of the cases
            break;
    }
    

    <a id="h-2-switch-statement-in-python"></a>

    2. Switch Statement in Python

    Python does not have a built-in switch statement like some other programming languages. However, there are several ways to achieve similar functionality in Python. Among them the match statement is very like the Switch Statement and can be a very good replacement.

    Python 3.10 introduced a new match statement that you can use to create switch-like structures. The match statement evaluates an expression and compares it to a series of patterns, executing the code associated with the first matching pattern.

    Before the match statement there were a few more replacements of the switch statements. Check them below.

    <a id="h-3-dictionary-replacement-of-switch-statement"></a>

    3. Dictionary - Replacement of Switch Statement

    In Python, dictionaries can be a useful replacement for switch statements. To use a dictionary as a switch-like structure, you can create a dictionary with keys representing the different cases and values representing the code to execute for each case. You can then use the get() method to look up the value associated with a particular key.

    Below is a general syntax of how we can use a python dictionary as a replacement for the Switch statement:

    
    # Using dictionary syntax
    def my_function(my_key, default_value=None):
        my_dict = {
            "key1": "value1",
            "key2": "value2",
            "key3": "value3"
        }
        result = my_dict.get(my_key, default_value)
        return result
    
    print(my_function("key1"))    
    # Output: value1
    
    print(my_function("key2"))    
    # Output: value2
    
    print(my_function("key4"))    
    # Output: None
    
    print(my_function("key4", 0)) 
    # Output: 0
    

    To better understand, we can have a more real-world example where we have used a Python dictionary as a replacement of switch statement.

    In the below example, we have define a calculate() function and a dictionary with keys. We use the get() method to look up the value associated with a particular key. If the operation is not found, we return an "Invalid operation" message.

    
    # Using dictionary
    def calculate(operation, num1, num2):
        switch = {
            "add": num1 + num2,
            "subtract": num1 - num2,
            "multiply": num1 * num2,
            "divide": num1 / num2
        }
        return switch.get(operation, "Invalid operation")
    
    print(calculate("add", 2, 3))       
    # Output: 5
    
    print(calculate("subtract", 7, 4))  
    # Output: 3
    
    print(calculate("multiply", 6, 8))  
    # Output: 48
    
    print(calculate("divide", 10, 5))   
    # Output: 2.0
    
    print(calculate("modulus", 3, 4))   
    # Output: Invalid operation
    

    <a id="h-4-switch-statement-with-classes"></a>

    4. Switch Statement with Classes

    Using classes is another approach to replacing switch statements in Python. You can define a class with methods corresponding to each case. The input value then determines which method is called.

    
    class MyClass:
        def case_1(self, arg1, arg2):
            # Put Code for This Case
            pass
    
        def case_2(self, arg1, arg2):
            # Put Code for This Case
            pass
    
        # Define more cases here
    
    def switch(case, arg1, arg2):
        my_class = MyClass()
        method = getattr(my_class, case, None)
        if method:
            return method(arg1, arg2)
        else:
            # Handle invalid case here
            pass
    

    Let's say we want to recreate our example from the previous topic using the Classes approach. We will have to create a class, in this case, we name it Calculator. We then added a few methods to the class, which corresponds to different operations.

    
    # Using getattr()
    class Calculator:
        def add(self, num1, num2):
            return num1 + num2
    
        def subtract(self, num1, num2):
            return num1 - num2
    
        def multiply(self, num1, num2):
            return num1 * num2
    
        def divide(self, num1, num2):
            return num1 / num2
    
    def calculate(operation, num1, num2):
        calculator = Calculator()
        method = getattr(calculator, operation, None)
        if method:
            return method(num1, num2)
        else:
            return "Invalid operation"
    
    print(calculate("add", 2, 3))       
    # Output: 5
    
    print(calculate("subtract", 7, 4))  
    # Output: 3
    
    print(calculate("multiply", 6, 8)) 
    # Output: 48
    
    print(calculate("divide", 10, 5))   
    # Output: 2.0
    
    print(calculate("modulus", 3, 4))   
    # Output: Invalid operation
    

    In the example above, the getattr() method gets the method corresponding to the given operation. If the method exists, we call it with the given arguments, and if it doesn't exist, we return an "Invalid operation" message.

    <a id="h-5-match-is-the-replacement-of-switch-statement"></a>

    5. "match" is the Replacement of Switch Statement

    In Python 3.10, the match statement was introduced as a replacement for the switch statement. The match statement allows for pattern matching and can handle more complex cases than a simple dictionary or if-elif statement.

    Below is the syntax of the mtach statement as a replacement for the switch statement.

    
    # match case syntax
    match variable:
        case pattern1:
            # Put Code for This Case
            pass
        case pattern2:
            # Put Code for This Case
            pass
        # Define more cases here
        case _:
            # handle invalid case here
            pass
    

    Once again, we recreated the same example with the match statement using the syntax of the match.

    
    # Using match case
    def calculate(operation, num1, num2):
        match operation:
            case "add":
                return num1 + num2
            case "subtract":
                return num1 - num2
            case "multiply":
                return num1 * num2
            case "divide":
                return num1 / num2
            case _:
                return "Invalid operation"
    
    print(calculate("add", 2, 3))       
    # Output: 5
    
    print(calculate("subtract", 7, 4))  
    # Output: 3
    
    print(calculate("multiply", 6, 8))  
    # Output: 48
    
    print(calculate("divide", 10, 5))   
    # Output: 2.0
    
    print(calculate("modulus", 3, 4))   
    # Output: Invalid operation
    

    <a id="h-6-switch-statement-with-if-else"></a>

    6. Switch Statement With if-else

    In cases where match statements are not available or we don't want to use a dictionary, we can use a combination of if-else statements to mimic the behavior of a switch statement in Python. While this approach can be more verbose than using a match statement, it can handle a wide variety of cases and is compatible with all versions of Python.

    
    # Using if elif else
    def calculate(operation, num1, num2):
        if operation == "add":
            return num1 + num2
        elif operation == "subtract":
            return num1 - num2
        elif operation == "multiply":
            return num1 * num2
        elif operation == "divide":
            return num1 / num2
        else:
            return "Invalid operation"
    
    print(calculate("add", 2, 3))       
    # Output: 5
    
    print(calculate("subtract", 7, 4))  
    # Output: 3
    
    print(calculate("multiply", 6, 8))  
    # Output: 48
    
    print(calculate("divide", 10, 5))   
    # Output: 2.0
    
    print(calculate("modulus", 3, 4))   
    # Output: Invalid operation
    

    <a id="h-7-summary-and-conclusion"></a>

    7. Summary and Conclusion

    We have covered different methods for replacing switch statements in Python, including using dictionaries, match statements, if-else statements, and classes. Though it depends on the use case where you want to use it, the match statement is still a more powerful and easy replacement for Switch Statement. I hope this article was helpful, please leave a comment if you have any questions.

    Happy Coding!