user
Switch case in Python ?
alphonsio

In Python, until 3.1, there is no direct equivalent to the switch-case statement found in other languages like C, C++, or Java. However, there is a solution to simulate switch-case functionality in Python.

Method 1: Using If-Elif-Else

In cases where you have only a few conditions or prefer a straightforward approach, using if-elif-else is simple and clear:

if case_id == 1:
    print("This is case one")
elif case_id == 2:
    print("This is case two")
elif case_id == 3:
    print("This is case three")
else:
    print("This is the default case")

Method 2: Using Python 3.10+ Match-Case

Starting from Python 3.10, the match statement serves as a switch-case equivalent, allowing pattern matching which is more versatile and powerful.

case_id = 1

match case_id:
    case 1:
        print("This is case one")
    case 2:
        print("This is case two")
    case 3:
        print("This is case three")
    case _:
        print("This is the default case")

Method 3: Using Dictionary Mapping

A common Pythonic approach to emulate a switch-case is through dictionary mapping, where dictionary keys act as cases, and values are functions or outcomes corresponding to each case.

def case_one():
    return "This is case one"

def case_two():
    return "This is case two"

def case_three():
    return "This is case three"

def default_case():
    return "This is the default case"

switch = {
    1: case_one,
    2: case_two,
    3: case_three
}

def switch_case(case_id):
    return switch.get(case_id, default_case)()

# Example usage
print(switch_case(1))  # Output: This is case one
print(switch_case(4))  # Output: This is the default case

Method 4: Using a Class

For a more structured and reusable approach, especially for complex scenarios, encapsulating the functionality in a class is a good design choice:

class Switcher:
    def switch(self, case_id):
        method_name = 'case_' + str(case_id)
        method = getattr(self, method_name, self.default_case)
        return method()

    def case_1(self):
        return "This is case one"

    def case_2(self):
        return "This is case two"

    def case_3(self):
        return "This is case three"

    def default_case(self):
        return "This is the default case"

# Example usage
switcher = Switcher()
print(switcher.switch(1))  # Output: This is case one
print(switcher.switch(4))  # Output: This is the default case