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

可能重复:
python中switch语句的替代?

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

你的兽医建议我用什么。 谢谢!


调度表,或者说是字典。

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

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

记得验证你的输入! :)


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

elif链

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

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

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

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

switchdict[input]()
链接地址: http://www.djcxy.com/p/42753.html

上一篇: Since Python doesn't have a switch statement, what should I use?

下一篇: What is the Python equivalent for a case/switch statement?