用python写菜单_用Python创建菜单

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

Print out a menu with numbered options

Let the user enter a numbered option

Depending on the option number the user picks, run a function specific to that action. For now, your function can just print out that it's being run.

If the user enters in something invalid, it tells the user they did so, and re-display the menu

use a dictionary to store menu options, with the number of the option as the key, and the text to display for that option as the value.

The entire menu system should run inside a loop and keep allowing the user to make choices until they select exit/quit, at which point your program can end.

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")

ANSWERED

This is what he wanted apparently:

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]()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值