三级菜单
菜单结构如下:
menu = { '北京':{ '海淀':{ '五道口':{ 'soho':{}, '网易':{}, 'google':{} }, '中关村':{ '爱奇艺':{}, '汽车之家':{}, 'youku':{}, }, '上地':{ '百度':{}, }, }, '昌平':{ '沙河':{ '老男孩':{}, '北航':{}, }, '天通苑':{}, '回龙观':{}, }, '朝阳':{}, '东城':{}, }, '上海':{ '闵行':{ "人民广场":{ '炸鸡店':{} } }, '闸北':{ '火车站':{ '携程':{} } }, '浦东':{}, }, '山东':{ '济南':{}, '大连':{}, }, '湖北':{ '武汉':{ '洪山区':{ '光谷':{} }, }, "黄冈":{ '黄州':{ '黄州中学':{}, '黄冈师范学院':{}, '遗爱湖':{}, }, }, }, }
程序要求:
可依次选择进入各子菜单
可从任意一层往回退到上一层
可从任意一层退出程序
基础入门版:
while True: ''' 死循环,一直运行 ''' for i in menu: ''' 打印第一层菜单 ''' print(i.center(10,'=')) choice1 = input('输入你的省市("q"退出)>>:').strip() if not choice1:continue # 未输入时一直等待 if choice1 in menu: ''' 判断输入是否存在 ''' while True: for i in menu[choice1]: ''' 打印第二层菜单 ''' print(i.center(20,'=')) # 居中显示 choice2= input('输入你的地区("r"返回,“q”退出)>>:').strip() if not choice2:continue if choice2 in menu[choice1]: while True: for i in menu[choice1][choice2]: ''' 打印第三层菜单''' print(i.center(30,'=')) choice3 = input('输入你的街道("r"返回,“q”退出)>>:').strip() if not choice3:continue if choice3 in menu[choice1][choice2]: while True: for i in menu[choice1][choice2][choice3]: ''' 打印第四层菜单 ''' print(i.center(40,'=')) choice4 = input('输入你的公司("r"返回,“q”退出)>>:').strip() if not choice4:continue if choice4 in menu[choice1][choice2][choice3]: while True: for i in menu[choice1][choice2][choice3][choice4]: ''' 打印第五层菜单 ''' print(i.center(50,'=')) choice = input("已到最后一层,按'r'返回,'q'退出>>:").strip() if not choice:continue if choice == 'r' or (choice == 'R'): ''' 当输入'r'或'R'时返回上一层 ''' break # 跳出当前循环 elif choice == 'q' or (choice == 'Q'): ''' 当输入'q'或'Q'时退出程序 ''' exit() # 退出程序 else: print("输入的选项不存在!") elif choice4 == 'r' or (choice4 == 'R'): break elif choice4 == 'q' or (choice4 == 'Q'): exit() else: print("输入的选项不存在!") elif choice3 == 'r' or (choice3 == 'R'): break elif choice3 == 'q' or (choice3 == 'Q'): exit() else: print("输入的选项不存在!") elif choice2 == 'r' or (choice2 == 'R'): break elif choice2 == 'q' or (choice2 == 'Q'): exit() else: print("输入的选项不存在!") elif choice1 == 'q' or (choice1 == 'Q'): exit() else: print('输入的选项不存在!')
豪华尊享版:
current_layer = menu # 记录当前层级位置 layers = [] # 记录每一层的位置 while True: for i in current_layer: print(i) choice = input('输入想去的地方(按"r"返回,"q"退出)>>>:').strip() if not choice:continue if choice in current_layer: layers.append(current_layer) # 将当前位置加到layers列表中 current_layer = current_layer[choice] # 更新当前层级的记录 elif choice == 'r' or (choice == 'R'): if len(layers) != 0: ''' 如果未到顶层时,返回''' current_layer = layers.pop() # 将layers列表的最后一项值赋给current_layer,即返回上一层 else: ''' 已到顶层,不可再返回 ''' print('你已经位到顶层了!') elif choice == 'q' or (choice == 'Q'): exit() # 退出程序 else: print("选项不存在!")
读书原为修身,正己才能正人正世;不修身不正己而去正人正世者,无一不是盗名欺世;你把念过的书能用上十之一二,就是很了不得的人了。——朱先生