可能重复:
python中switch语句的替换?
我在Python中创建一个基于控制台的小应用程序,我想使用Switch语句来处理用户对菜单选择的选择.
你有什么建议我用的.谢谢!
Omn*_*ous 10
有两种选择,首先是标准if ... elif ...链.另一个是字典映射选择到callables(函数是一个子集).取决于你正在做什么,哪个是更好的主意.
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()
Run Code Online (Sandbox Code Playgroud)
字典:
# 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()
Run Code Online (Sandbox Code Playgroud)
使用字典将输入映射到函数.
switchdict = { "inputA":AHandler, "inputB":BHandler}
Run Code Online (Sandbox Code Playgroud)
处理程序可以是任何可调用的.然后你像这样使用它:
switchdict[input]()
Run Code Online (Sandbox Code Playgroud)
派遣表,或者说字典.
你映射键也称.菜单选择的值到执行所述选择的功能:
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']()
Run Code Online (Sandbox Code Playgroud)
请记住验证您的输入!:)
| 归档时间: |
|
| 查看次数: |
5389 次 |
| 最近记录: |