In Python, there's no built-in switch-case statement like in some other languages, but you can implement similar behavior using various approaches. Here are three ways to achieve this:

1. Using a Dictionary

One of the most common and Pythonic ways to implement a switch-case-like structure is by using a dictionary of functions or values

def switch_case_example(value):
    switcher = {
        1: "Case 1",
        2: "Case 2",
        3: "Case 3",
    }
    return switcher.get(value, "Default case")

# Example usage:
print(switch_case_example(2))  # Output: Case 2

2. Using if-elif-else Ladder

This method is straightforward and doesn't require any additional constructs. It’s more verbose but works well for simpler cases.

def switch_case_example(value):
    if value == 1:
        return "Case 1"
    elif value == 2:
        return "Case 2"
    elif value == 3:
        return "Case 3"
    else:
        return "Default case"

# Example usage:
print(switch_case_example(2))  # Output: Case 2

3. Using Classes with Methods

For more complex scenarios, you can define a class with methods that act as different cases. This approach is beneficial when each case involves more elaborate logic.

class SwitchCaseExample:
    def case_1(self):
        return "Case 1"
    
    def case_2(self):
        return "Case 2"
    
    def case_3(self):
        return "Case 3"
    
    def default_case(self):
        return "Default case"

    def switch(self, value):
        method_name = f'case_{value}'
        method = getattr(self, method_name, self.default_case)
        return method()

# Example usage:
switch_case = SwitchCaseExample()
print(switch_case.switch(2))  # Output: Case 2

These three methods provide flexibility in how you can implement switch-case functionality in Python, depending on your specific needs and the complexity of your cases.

Simon

102 Articles

I love talking about tech.