多级菜单

  • 三级菜单
  • 可依次选择进入各子菜单
  • 所需新知识点:列表、字典
 1 menu = {
 2     '北京':{
 3         '海淀':{
 4             '五道口':{
 5                 'soho':{},
 6                 '网易':{},
 7                 'google':{}
 8             },
 9             '中关村':{
10                 '爱奇艺':{},
11                 '汽车之家':{},
12                 'youku':{},
13             },
14             '上地':{
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 }
 1 while True:
 2     for key in menu:
 3         print(key)
 4     choice = input(">>:").strip()
 5     if len(choice) == 0:continue
 6     if choice == "b":break
 7     if choice not in menu:continue
 8 
 9     while True:
10         for key2 in menu[choice]:
11             print(key2)
12         choice2 = input(">>:").strip()
13         if len(choice2) == 0: continue
14         if choice2 == "b": break
15         if choice2 not in menu[choice]: continue
16 
17         while True:
18             for key3 in menu[choice][choice2]:
19                 print(key3)
20             choice3 = input(">>:").strip()
21             if len(choice3) == 0: continue
22             if choice3 == "b": break
23             if choice3 == "q": exit()
24             if choice3 not in menu[choice][choice2]: continue
25 
26             while True:
27                 for key4 in menu[choice][choice2][choice3]:
28                     print(key4)
29                 choice4 = input(">>:").strip()
30                 if len(choice4) == 0: continue
31                 if choice4 == "b": break
32                 if choice4 not in menu[choice][choice2][choice3]: continue
 1 current_level = menu
 2 last_levels = []
 3 while True:
 4     for key in current_level:
 5         print(key)
 6     choice = input(">>:").strip()
 7     if len(choice) == 0: continue
 8     if choice == "b":
 9     #     current_level = last_level #把当前层改成父亲层,这样下一次循环就回到上一层
10         #if not last_levels :break
11         if len(last_levels) == 0 :break
12         current_level = last_levels[-1]
13         last_levels.pop()
14     if choice not in current_level:continue
15     # last_level = current_level #记住当前层
16     last_levels.append(current_level)
17     current_level = current_level[choice] #进入下一层

  

原文地址:https://www.cnblogs.com/wangmo/p/6109272.html