Python - Switch Case Implementation


Advertisements

Unlike C++/Java, Python does not have a in-built switch case statement. Due to this, it is quite common to think of using if-elif-else control statement for each switch cases. But there is a other way around to implement switch statement in Python. The powerful dictionary mapping which provides unique key-value mapping can be efficiently used to create such implementation.

Example:

The below example illustrates how to implement switch case in Python. Inside the function called MySwitchCases, the dictionary called MyDict is created with key-value pairs representing respective switch-case scenarios. When the function MySwitchCases is called, it uses dictionary get() method to find the value of the specified key. If the key is not present in the dictionary, it returns default value which is "Not Found" in this particular example.

def MySwitchCases(case):
    MyDict = {
        1: 'MON',
        2: 'TUE',
        3: 'WED',
        4: 'THU',
        5: 'FRI',
        6: 'SAT',
        7: 'SUN'
    }
    return MyDict.get(case, 'Not Found')
print(MySwitchCases(3))

print(MySwitchCases(10))

Output

WED

Not Found
Advertisements