作业题目: 三级菜单
- 作业需求:
menu = { ‘北京‘:{ ‘海淀‘:{ ‘五道口‘:{ ‘soho‘:{}, ‘网易‘:{}, ‘google‘:{} }, ‘中关村‘:{ ‘爱奇艺‘:{}, ‘汽车之家‘:{}, ‘youku‘:{}, }, ‘上地‘:{ ‘百度‘:{}, }, }, ‘昌平‘:{ ‘沙河‘:{ ‘优衣库‘:{}, ‘北航‘:{}, }, ‘天通苑‘:{}, ‘回龙观‘:{}, }, ‘朝阳‘:{}, ‘东城‘:{}, }, ‘上海‘:{ ‘闵行‘:{ "人民广场":{ ‘炸鸡店‘:{} } }, ‘闸北‘:{ ‘火车站‘:{ ‘携程‘:{} } }, ‘浦东‘:{}, }, ‘山东‘:{}, }
需求: 可依次选择进入各子菜单 可从任意一层往回退到上一层 可从任意一层退出程序 所需新知识点:列表、字典 基础版:
while True: for i in menu: print(i) province = input("请选择省份: (按Q退出)") if province == ‘Q‘: exit() else: print(‘输入错误‘) if province in menu: while True: for i in menu[province]: print(i) city = input("请选择市: (按Q退出,q返回)") if city == ‘Q‘: exit() if city == ‘q‘: break else: print(‘输入错误‘) if city in menu[province]: while True: for i in menu[province][city]: print(i) county = input("请选择区或县: (按Q退出,q返回)") if county == ‘Q‘: exit() if county == ‘q‘: break else: print(‘输入错误‘) if county in menu[province][city]: while True: for i in menu[province][city][county]: print(i) choice = input(‘Q退出,q返回:‘) if choice == ‘Q‘: exit() if choice == ‘q‘: break else: print(‘输入错误‘)
装逼版:
rank = menu last_rank = [] while True: for i in rank: print(i) choice = input(‘>:‘).strip() if choice in rank: last_rank.append(rank) # 将当前菜单添加到列表 rank = rank[choice] # 进入下一层菜单 elif choice == ‘b‘: if len(last_rank) != 0: rank = last_rank.pop() # 删除列表最后一位元素,从而返回上一层 elif choice == ‘Q‘: exit()
最里层和最外层还可以增加相应提示。
原文地址:https://www.cnblogs.com/zivli/p/9064696.html
时间: 2024-10-03 17:26:06