Creating a Menu in Python(在 Python 中创建菜单)
问题描述
我正在用 python 制作一个菜单,需要:
I'm working on making a menu in python that needs to:
- 打印带有编号选项的菜单
- 让用户输入编号选项
- 根据用户选择的选项编号,运行特定于该操作的函数.现在,您的函数可以打印出它正在运行.
- 如果用户输入了无效的内容,它会告诉用户他们输入了,并重新显示菜单
- 使用字典来存储菜单选项,以选项编号作为键,以该选项显示的文本作为值.
- 整个菜单系统应该在一个循环内运行,并不断允许用户做出选择,直到他们选择退出/退出,此时您的程序可以结束.
我是 Python 新手,无法弄清楚我在代码中做错了什么.
I'm new to Python, and I can't figure out what I did wrong with the code.
到目前为止,这是我的代码:
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("
Student Added")
elif ans=="2":
print("
Student Deleted")
elif ans=="3":
print("
Student Record Found")
elif ans=="4":
print("
Goodbye")
elif ans !="":
print("
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!"
推荐答案
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]()
这篇关于在 Python 中创建菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!