【发布时间】:2013-11-26 16:38:03
【问题描述】:
我正在用 python 制作一个菜单,需要:
- 打印带有编号选项的菜单
- 让用户输入带编号的选项
- 根据用户选择的选项编号,运行特定于该操作的函数。目前,您的函数可以打印出它正在运行。
- 如果用户输入了无效的内容,它会告诉用户他们这样做了,并重新显示菜单
- 使用字典存储菜单选项,以选项的编号作为键,为该选项显示的文本作为值。
- 整个菜单系统应该在一个循环中运行,并一直允许用户做出选择,直到他们选择退出/退出,此时您的程序可以结束。
我是 Python 新手,我不知道我在代码中做错了什么。
到目前为止,这是我的代码:
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")
回答
这显然是他想要的:
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!"
【问题讨论】:
-
ans=input("What would you like to do?")
-
而且你的打印字符串上有太多引号......你也没有使用字典或作业需要的任何其他东西
-
我应该有多少报价?就像我说的,我是 Python 新手,基本上已经不再使用在线教程了。
-
else: print("\n Not Valid Choice Try again")你不需要 elif。 -
另外,在选项 4 上,您需要一个“break”命令来退出循环。