Python doesn’t have the syntax of switch. therefore the question arose on how this might be done in python. In Python the switch-case statement doesn’t exist.

So how are you able to use switch in Python, that’s known in Java and others?

Related Course: Complete Python Programming Course & Exercises

Switch case

Simple if-else

There are if statements in python, and when learning C, the choice to if-else switch, and therefore the two can perfectly replace one another , note that in python else if is simplified to elif, as follows.

#!/usr/bin/env python

user_cmd = input("please input your choice:\n")
if usercmd == "select"
ops = "select"
elif usercmd == "update"
ops = "update"
elif usercmd == "delete"
ops = "delete"
elif usercmd == "insert"
ops = "insert"
else
ops = "invalid choice!"
print(ops)

python switch case

Use dictionaries

You can utilize the dictionary function: dict.get(key, default=None).
Where key is the value to be searched within the dictionary.

#!/usr/bin/env python

usercmd = input("please input your choice:\n")
dic = {'select':'select action','update':'update action','delete':'delete action','insert':'insert action'}
defaultitem = 'invalid choice!'
ops = dic.get(usercmd,defaultitem)
print(ops)

Use lambda function combined with dictionary

The general syntax of lambda is that the keyword lambda followed by one or more arguments, followed by a colon, followed by an expression.

You can use a lambda expression with a dictionary to simulate a switch statement.

#!/usr/bin/env python

usrcmd = input("please input your choice: \n")

dic = {'select': lambda : "select action"
'update': lambda : "update action",
'delete': lambda : "delete action",
'insert': lambda : "insert action"}
print(cho[usr_cmd]())

Related Course: Complete Python Programming Course & Exercises