Creating a Menu in Python(在 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 中创建菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:在 Python 中创建菜单


基础教程推荐
猜你喜欢
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01