由于Python没有switch语句,我应该使用什么?

时间:2010-10-20 13:56:58

标签: python switch-statement

  

可能重复:
  Replacements for switch statement in python?

我在Python中创建一个基于控制台的小应用程序,我想使用Switch语句来处理用户对菜单选择的选择。

你有什么建议我使用。谢谢!

3 个答案:

答案 0 :(得分:10)

有两种选择,第一种是标准if ... elif ...链。另一个是字典映射选择到callables(函数是一个子集)。取决于你正在做什么,哪个是更好的主意。

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()

词典:

 # 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()

答案 1 :(得分:8)

使用字典将输入映射到函数。

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

处理程序可以是任何可调用的。然后你就像这样使用它:

switchdict[input]()

答案 2 :(得分:7)

发送表格,或者说字典。

你也可以映射键。菜单选择的值到执行所述选择的功能:

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']()

请记住验证您的输入! :)