Since Python doesn’t have a switch statement, what should I use? – Education Career Blog

Possible Duplicate:
Replacements for switch statement in python?

I’m making a little console based application in Python and I wanted to use a Switch statement to handle the users choice of a menu selection.

What do you vets suggest I use. Thanks!

,

There are two choices, first is the standard if ... elif ... chain. The other is a dictionary mapping selections to callables (of functions are a subset). Depends on exactly what you’re doing which one is the better idea.

elif chain

 selection = get_input()
 if selection == 'option1':
      handle_option1()
 elif selection == 'option2':
      handle_option2()
 elif selection == 'option3':
      some = code + that
      does(something) for something in range(0, 3)
 else:
      I_dont_understand_you()

dictionary:

 # Somewhere in your program setup...
 def handle_option3():
    some = code + that
    does(something) for something in range(0, 3)

 seldict = {
    'option1': handle_option1,
    'option2': handle_option2,
    'option3': handle_option3
 }

 # later on
 selection = get_input()
 callable = seldict.get(selection)
 if callable is None:
      I_dont_understand_you()
 else:
      callable()

,

Use a dictionary to map input to functions.

switchdict = { "inputA":AHandler, "inputB":BHandler}

Where the handlers can be any callable. Then you use it like this:

switchdictinput()

,

Dispatch tables, or rather dictionaries.

You map keys aka. values of the menu selection to functions performing said choices:

def AddRecordHandler():
        print("added")
def DeleteRecordHandler():
        print("deleted")
def CreateDatabaseHandler():
        print("done")
def FlushToDiskHandler():
        print("i feel flushed")
def SearchHandler():
        print("not found")
def CleanupAndQuit():
        print("byez")

menuchoices = {'a':AddRecordHandler, 'd':DeleteRecordHandler, 'c':CreateDatabaseHandler, 'f':FlushToDiskHandler, 's':SearchHandler, 'q':CleanupAndQuit}
ret = menuchoicesinput()()
if ret is None:
    print("Something went wrong! Call the police!")
menuchoices'q'()

Remember to validate your input! 🙂

Leave a Comment