I did a read through various books and blogs, come to conclusion that this is best. I am still don't know if there is better to implement switch function in python. I want to edit this question as some one marked it as Duplicate. I want this question to be answered with one-right answer where any one can search and find one best answer to implement switch statement in python. That will prevent user for searching around many blogs , forum or many books to find answer. As per Pythonic way, each problem will have one single best answer.
class MyAppLookupError(LookupError):
'''raise this when there's a lookup error for my app'''
print "exception occured"
if (LookupError =='001'):
print "There is something to fix"
def PrintBlue():
print (" You chose Blue!\r\n")
def PrintRed():
print (" You chose Red!\r\n")
def PrintOrange():
print (" You chose Orange!\r\n")
def PrintYellow():
print (" You chose Yellow!\r\n")
#Let's create a dictionary with unique key
ColorSelect = {
0:PrintBlue,
1:PrintRed,
2:PrintOrange,
3:PrintYellow
}
Selection = 0
while (True):
print ("0.Blue")
print ("1.Red")
print ("2.Orange")
print ("3.Yellow")
try:
Selection = int(input("Select a color option: "))
x=0
if ( Selection < 0) or (Selection > 3):
raise MyAppLookupError(" Enter a number >=0 and <4)")
except MyAppLookupError as er:
print er
else:
ColorSelect[Selection]() # Run the function inside dictionary as well
finally:
pass
There is another way to do is by using if-then-else statement