Switch statement in Python

Ashu Anand
2 min readApr 19, 2022

While working on one of my own project, I had a requirement where I wanted my program to execute some function randomly. This is a perfect example of using Case statement but being on Python 3.7, this was not possible.

So, my alternative was to use nested If-Else, which was out of scope for me due to putting so many conditions. I remembered about using Dictionary and using it inside a function which can return me the actual function which I want to use. I thought of sharing it everyone, as it might be useful for someone.

If-Else statement

First I have defined my functions which I want to use based on what user choice.

def Function_1():
return 'Function_1'
def Function_2():
return 'Function_2'
def Function_3():
return 'Function_3'
def Function_4():
return 'Function_4'
def Function_5():
return 'Function_5'

Now, I will define one more function which will actually be returning me my chosen function.

def Select_Function(p_choice):
p_fun_dict={1:Function_1(),
2:Function_2(),
3:Function_3(),
4:Function_4(),
5:Function_5()}
return p_fun_dict.get(p_choice)

In the above code as you can see, I have placed my actual function names inside the dictionary. I can use the dictionary without my select function as well as below

p_fun_dict_out={1:Function_1(),
2:Function_2(),
3:Function_3(),
4:Function_4(),
5:Function_5()
}

Once done we can call our function with any of below code.

from random import choiceprint(Select_Function(choice([1,5,2,4,3])))
print(p_fun_dict_out[choice([1,5,2,4,3])])

Try the same at your end and it might make your code less bulky.

Also, luckily with python 3.10 we know have the capability to use actual case statement just like we can use it other programming languages.

--

--

Ashu Anand

Developer, Engineer and an Analyst who is enthusiast enough to try new thing. Love to play sports and developing my Trading bot.