-1

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

k.b
  • 125
  • 2
  • 12
  • Using a dictionary is probably the most efficient way of achieving this. Altough, instead of the `if ( Selection < 0) or (Selection > 3):` I'd simply use a `try: ... except KeyError`. – DeepSpace Jul 04 '17 at 08:47
  • Whats wrong with `if/elif` ? – Oasa Jul 04 '17 at 08:48
  • @Oasa Long, messy code that in the worst case will need to make `O(n)` checks (imagine the input being 90% of the times the last `elif`) instead of `O(1)` with the dictionary. – DeepSpace Jul 04 '17 at 08:49
  • @DeepSpace , Sorry for being noob, what is `O(n)`. If I have to take a guess, are you referring to the n number of if statement that it has to go through before reaching the desired soln? – Oasa Jul 04 '17 at 08:52
  • @Oasa yes, exactly that. – DeepSpace Jul 04 '17 at 08:54
  • Though there are cases where a unique key can not be created - e.g. if you need to do checks with ``isinstance``. In such a case you would have to fall back to if..elif..else – Mike Scotty Jul 04 '17 at 08:54
  • We already have a canonical question and answer, we don't need another canonical question and answer. – deceze Jul 04 '17 at 09:13

0 Answers0