如何将多个输入分配到一个if / else语句
示例:
print ("quit = quits the program")
print ("stay = stays in the program")
choose = input("I choose: ")
if choose == "quit":
quit
else:
print ("What is that")
if choose == "stay":
print (" ") #Prints nothing so basically its not going to quit
else:
print ("What is that")
所以是的,基本上我要做的就是设置多项选择权,所以当你在我选择框中写退出时它会退出,当你写下留下时它会打印出任何东西,所以它&& #39;不会退出。
顺便说一句:当我按照我在示例中所做的那样做时,它无法正常工作。
答案 0 :(得分:2)
在我的一个程序中,我提出了一种更复杂的选择方法。 它涉及每个选项链接到特定功能。
想象一下,我希望用户选择以下功能之一:
def Quit():
print "goodbye"
os._exit(1)
def say_hello():
print "Hello world!"
def etcetera():
pass
我用key作为用户输入关键字创建一个字典,值是一个描述和一个函数。在这种情况下,我使用字符串数字
OPTIONS = {"0":dict( desc = "Quit", func = Quit),
"1":dict( desc = "Print hello", func = say_hello),
"2":dict( desc = "Another example", func = etcetera)}
然后我的菜单功能看起来像这样!
def main_menu():
while True:
print "\nPlease choose an option:"
for key in sorted(OPTIONS.keys()):
print "\t" + key + "\t" + OPTIONS[key]["desc"]
input = raw_input("Selection: ")
if not input in OPTIONS.keys():
print "Invalid selection"
else:
OPTIONS[input]["func"]()
>>>main_menu()
Please choose an option
0 Quit
1 Print hello
2 Another example
Selection: 1
Hello world!
Please choose an option
0 Quit
1 Print hello
2 Another example
Selection: 0
goodbye
>>>
修改强> 或者,您可以创建一个返回关键字,以便您可以使用嵌套菜单。
OPTIONS = {"0":dict( desc = "Quit", func = Quit),
"1":dict( desc = "Go to menu 2", func = menu_2),
OPTIONS2 = {"1":dict( desc = "Another example", func = etcetera)}
def main_menu():
while True:
print "\nPlease choose an option:"
for key in sorted(OPTIONS.keys()):
print "\t" + key + "\t" + OPTIONS[key]["desc"]
input = raw_input("Selection: ")
if not input in OPTIONS.keys():
print "Invalid selection"
else:
OPTIONS[input]["func"]()
def main_2():
while True:
print "\nPlease choose an option :"
print "\t0\tReturn"
for key in sorted(OPTIONS2.keys()):
print "\t" + key + "\t" + OPTIONS2[key]["desc"]
input = raw_input("Selection: ")
if input == '0':
return
if not input in OPTIONS2.keys():
print "Invalid selection"
else:
OPTIONS2[input]["func"]()
>>>main_menu()
Please choose an option
0 Quit
1 Go to menu 2
Selection: 1
Please choose an option
0 Return
1 Another example
Selection: 0
Please choose an option
0 Quit
1 Go to menu 2
Selection: 0
goodbye
>>>
答案 1 :(得分:1)
我认为你的意思是这样的 - 你可以通过以下方式简化你的代码。:
if choose == "quit":
quit() # Notice the brackets to call the function.
elif choose == "stay":
print (" ")
else:
print ("What is that")
在上面的示例中,我已经修改过,因此退出'如果输入了函数quit()
,则程序退出。因为它只会打印函数对象的字符串表示。
此外,您可以使用if: ... else:
合并条件elif
语句。只检查前面的条件语句是否未执行时才会检查,因此这里很完美。考虑到这一点,也只需要进行else
一次。