Since Python does not have a switch statement, what should I use?

Possible duplicate:
Replacements for switch statement in python?

I am creating a small Python console application, and I wanted to use the Switch statement to handle the user's choice of menu choices.

What do you vets offer me to use. Thanks!

+7
python switch-statement
source share
3 answers

Dispatch tables, or rather dictionaries.

You also stick keys. menu selection values ​​for functions that perform these options:

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 = menuchoices[input()]() if ret is None: print("Something went wrong! Call the police!") menuchoices['q']() 

Do not forget to confirm your entry! :)

+7
source share

There are two options: the first standard if ... elif ... chain. Another is the choice of displaying a dictionary for called objects (functions are a subset). Depending on what you do, this is a 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() 

vocabulary:

  # 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() 
+10
source share

Use the dictionary to display function input.

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

If handlers can be any called. Then you use it as follows:

 switchdict[input]() 
+8
source share

All Articles