用Python创建菜单 [英] Creating a Menu in Python

查看:132
本文介绍了用Python创建菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python创建菜单,该菜单需要:

I'm working on making a menu in python that needs to:

  1. 打印出带有编号选项的菜单
  2. 让用户输入一个编号选项
  3. 根据用户选择的选项号,运行特定于该操作的功能.现在,您的函数可以只打印出它正在运行.
  4. 如果用户输入的内容无效,它会告诉用户他们输入了无效内容,然后重新显示菜单
  5. 使用词典存储菜单选项,以选项的编号作为键,并以显示该选项的文本作为值.
  6. 整个菜单系统应在一个循环内运行,并保持允许用户进行选择,直到他们选择退出/退出为止,这时您的程序可以结束.

我是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("\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!" 

推荐答案

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创建菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆