Home » Data Science » Python » Python Switch Case

Newly Updated Posts

Python Switch Case

Python doesn’t have a built-in switch-case statement like some other programming languages. However, you can achieve similar functionality using other constructs. Here are a few ways to implement a switch-case-like behavior in Python:

1. If-elif-else ladder:

def switch_case(value):
    if value == 'case1':
        # code for case 1
        pass
    elif value == 'case2':
        # code for case 2
        pass
    elif value == 'case3':
        # code for case 3
        pass
    else:
        # default case
        pass

2. Dictionary mapping:

def switch_case(value):
    cases = {
        'case1': lambda: code_for_case1(),
        'case2': lambda: code_for_case2(),
        'case3': lambda: code_for_case3(),
    }
    cases.get(value, lambda: default_case_code())()

In this approach, the cases are defined as keys in the dictionary, and the corresponding code is wrapped in lambda functions. The get() method is used to retrieve the appropriate lambda function based on the given value. If the value doesn’t match any case, a lambda function for the default case is called.

3. Using classes and methods:

class SwitchCase:
    def case1(self):
        # code for case 1
        pass

    def case2(self):
        # code for case 2
        pass

    def case3(self):
        # code for case 3
        pass

def switch_case(value):
    switch = SwitchCase()
    getattr(switch, value, lambda: default_case_code())()

In this approach, you define a class with methods representing each case. The getattr() function is used to retrieve the appropriate method based on the given value. If the value doesn’t match any case, a lambda function for the default case is called.

Choose the approach that best suits your needs and coding style.