Python Switch Case


Python Switch Case

Despite the fact that numerous different dialects offer switch explanations, python doesn’t have any switch articulation. As per PEP-3103, it guarantee about the reality. Notwithstanding on the off chance that you like switch case proclamation in other programming dialects, you can make code bit that works like a switch case articulation in python.

Using Dictionary to Return value

You can use dictionary to work like a switch statement. Here the keys of the dictionary will work as case.

At that point as indicated by the keys, the estimation of the dictionary will fill in as the outcome. We will give some model all through this instructional exercise. See the accompanying code to comprehend this straightforward illustration of switch case proclamation elective. See our Python Dictionary instructional exercise, in the event that you don’t think about Python dictionary.

b ={
    'a' : 122,
    'b' : 123,
    'c' : 124,
    'd' : 125

# take user input
inp = input('input a character : ')

# -1 is the default value if there is no keys that matches the input
print('The result for inp is : ', b.get(inp, -1))

So for my case I entered ‘b’ as input. The output was following

Python switch case statement alternative with dynamic functions

In this part we will perceive how to perform dynamic activity dependent on dictionary keys. Thus, envision a situation where we have to ascertain distinctive thing dependent on the information. How to do that utilizing dictionary? All things considered, in this case we will utilize Python Lambda capacity to do that. Consider the to be model as an option of python switch case explanation.

def switch_func(value, x):
    return {
        'a': lambda x: x+122,
        'b': lambda x: x*2,
        'c': lambda x: x-123,
        'd': lambda x: x/2

# take user input
inp = input('input a character : ')

print('The result for inp is : ', switch_func(inp, 2))

I used ‘d’ as input. So the output of the following code was like this

input a character : d
The result for inp is :  1.0

So, that’s all about Python switch case statement alternatives. It’s not recommended to use this kind of code snippet. Python if else technique is more elegant to use than this snippet. But it is never bad to learn about new techniques.