Python实现三级菜单

需求:
    可依次选择进入各子菜单
    可从任意一层往回退到上一层
    可从任意一层退出程序
    所需新知识点:列表、字典
只用一个while循环

 1 #! -*- coding:utf-8 -*-
 2 
 3 menu = {
 4     '北京': {
 5         '海淀': {
 6             '五道口': {
 7                 'soho': {},
 8                 '网易': {},
 9                 'google': {}
10             },
11             '中关村': {
12                 '爱奇艺': {},
13                 '汽车之家': {},
14                 'youku': {},
15             },
16             '上地': {
17                 '百度': {},
18             },
19         },
20         '昌平': {
21             '沙河': {
22                 '老男孩': {},
23                 '北航': {},
24             },
25             '天通苑': {},
26             '回龙观': {},
27         },
28         '朝阳': {},
29         '东城': {},
30     },
31     '上海': {
32         '闵行': {
33             "人民广场": {
34                 '炸鸡店': {}
35             }
36         },
37         '闸北': {
38             '火车战': {
39                 '携程': {}
40             }
41         },
42         '浦东': {},
43     },
44     '山东': {},
45 }
46 current_layer = menu  # 实现动态循环
47 parent_layer = []  # 保留所有父层,最后一个元素永远为父层
48 
49 while True:
50     print('-' * 10, "菜单", '-' * 10)
51     for i in current_layer:  # 遍历打印地址
52         print(i)
53     print("请在下方输入菜单名称,或 b:返回上一层,q:退出\n", '-' * 26)
54     choice = input(" >>> ").strip()
55     if choice in current_layer:
56         if current_layer[choice]:  # 判断是否为末层
57             parent_layer.append(current_layer)  # 进入子层前,添加当前层作为父层
58             current_layer = current_layer[choice]  # 修改子层
59         else:
60             print('当前是最后一页')
61     elif choice == '':
62         continue
63     elif choice == 'b' or choice == 'B':  # 返回上层
64         if parent_layer:  # 判断 parent_layer 是否为空
65             current_layer = parent_layer.pop()  # 取出当前层父层
66     # 退出循环
67     elif choice == 'q' or choice == 'Q':
68         break
69     else:
70         print("\033[34;1m输入有误,请重新输入\033[0m")

猜你喜欢

转载自www.cnblogs.com/shihun/p/9219240.html
今日推荐