在Python中创建菜单

Jac*_*ack 12 python menu

我正在努力在python中创建一个需要的菜单:

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

我是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") 
Run Code Online (Sandbox Code Playgroud)

ANSWERED

这显然是他想要的:

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!" 
Run Code Online (Sandbox Code Playgroud)

Jor*_*ley 9

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]()
Run Code Online (Sandbox Code Playgroud)


Chr*_*ser 7

只需要几个小修改:

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") 
Run Code Online (Sandbox Code Playgroud)

我已将四个引号更改为三个(这是多行引号所需的数字),之后添加了一个结束括号"What would you like to do? "并将输入更改为raw_input.


jra*_*rez 5

这应该做到这一点.你错过了一个),你只需要其中的"""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")
Run Code Online (Sandbox Code Playgroud)