在 Python 中创建菜单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19964603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a Menu in Python
提问by Hyman
I'm working on making a menu in python that needs to:
我正在用 python 制作一个菜单,它需要:
- Print out a menu with numbered options
- Let the user enter a numbered option
- Depending on the option number the user picks, run a function specific to that action. For now, your function can just print out that it's being run.
- If the user enters in something invalid, it tells the user they did so, and re-display the menu
- use a dictionary to store menu options, with the number of the option as the key, and the text to display for that option as the value.
- The entire menu system should run inside a loop and keep allowing the user to make choices until they select exit/quit, at which point your program can end.
- 打印带有编号选项的菜单
- 让用户输入编号选项
- 根据用户选择的选项编号,运行特定于该操作的函数。现在,您的函数可以打印出它正在运行。
- 如果用户输入了无效的内容,它会告诉用户他们这样做了,并重新显示菜单
- 使用字典来存储菜单选项,以选项编号作为键,以该选项显示的文本作为值。
- 整个菜单系统应该在循环内运行,并继续允许用户进行选择,直到他们选择退出/退出,此时您的程序可以结束。
I'm new to Python, and I can't figure out what I did wrong with the code.
我是 Python 的新手,我无法弄清楚我在代码中做错了什么。
So far this is my code:
到目前为止,这是我的代码:
ans=True
while ans:
print (""""
1.Add a Student
2.Delete a Student
3.Look Up Student Record
4.Exit/Quit
"""")
ans=input("What would you like to do?"
if ans=="1":
print("\nStudent Added")
elif ans=="2":
print("\n Student Deleted")
elif ans=="3":
print("\n Student Record Found")
elif ans=="4":
print("\n Goodbye")
elif ans !="":
print("\n Not Valid Choice Try again")
ANSWERED
回答
This is what he wanted apparently:
这显然是他想要的:
menu = {}
menu['1']="Add Student."
menu['2']="Delete Student."
menu['3']="Find Student"
menu['4']="Exit"
while True:
options=menu.keys()
options.sort()
for entry in options:
print entry, menu[entry]
selection=raw_input("Please Select:")
if selection =='1':
print "add"
elif selection == '2':
print "delete"
elif selection == '3':
print "find"
elif selection == '4':
break
else:
print "Unknown Option Selected!"
回答by ChrisProsser
There were just a couple of minor amendments required:
只需要进行一些小的修改:
ans=True
while ans:
print ("""
1.Add a Student
2.Delete a Student
3.Look Up Student Record
4.Exit/Quit
""")
ans=raw_input("What would you like to do? ")
if ans=="1":
print("\n Student Added")
elif ans=="2":
print("\n Student Deleted")
elif ans=="3":
print("\n Student Record Found")
elif ans=="4":
print("\n Goodbye")
elif ans !="":
print("\n Not Valid Choice Try again")
I have changed the four quotes to three (this is the number required for multiline quotes), added a closing bracket after "What would you like to do? "
and changed input to raw_input.
我已将四个引号更改为三个(这是多行引号所需的数字),在后面添加了一个右括号"What would you like to do? "
并将输入更改为 raw_input。
回答by jramirez
This should do it. You were missing a )
and you only need """
not 4 of them. Also you don't need a elif at the end.
这应该做。你错过了一个)
,你只需要其中的"""
4 个。最后你也不需要 elif 。
ans=True
while ans:
print("""
1.Add a Student
2.Delete a Student
3.Look Up Student Record
4.Exit/Quit
""")
ans=raw_input("What would you like to do? ")
if ans=="1":
print("\nStudent Added")
elif ans=="2":
print("\n Student Deleted")
elif ans=="3":
print("\n Student Record Found")
elif ans=="4":
print("\n Goodbye")
ans = None
else:
print("\n Not Valid Choice Try again")
回答by Joran Beasley
def my_add_fn():
print "SUM:%s"%sum(map(int,raw_input("Enter 2 numbers seperated by a space").split()))
def my_quit_fn():
raise SystemExit
def invalid():
print "INVALID CHOICE!"
menu = {"1":("Sum",my_add_fn),
"2":("Quit",my_quit_fn)
}
for key in sorted(menu.keys()):
print key+":" + menu[key][0]
ans = raw_input("Make A Choice")
menu.get(ans,[None,invalid])[1]()
回答by JFA
It looks like you've just finished step 3. Instead of running a function, you just print out a statement. A function is defined in the following way:
看起来您刚刚完成了第 3 步。您只需打印出一条语句,而不是运行函数。函数定义如下:
def addstudent():
print("Student Added.")
then called by writing addstudent()
.
然后通过写作调用addstudent()
。
I would recommend using a while
loop for your input. You can define the menu option outside the loop, put the print statement inside the loop, and do while(#valid option is not picked)
, then put the if statements after the while. Or you can do a while
loop and continue
the loop if a valid option is not selected.
我建议while
为您的输入使用循环。您可以在循环外定义菜单选项,将打印语句放在循环内,然后 do while(#valid option is not picked)
,然后将 if 语句放在 while 之后。或者,如果未选择有效选项,您可以执行while
循环和continue
循环。
Additionally, a dictionary is defined in the following way:
此外,字典的定义方式如下:
my_dict = {key:definition,...}