实现要求:
- 三级菜单
- 可依次选择进入各子菜单
- 所需知识点:列表、字典
1 #!/usr/local/env python3 2 # -*- coding:utf-8 -*- 3 ''' 4 Author:@Alvin Lv 5 Blog:http://www.cnblogs.com/Xiaolong-Lv/ 6 E-mail:lxtxlxl@163.com 7 ''' 8 import sys 9 CityList ={ 10 "华北地区":{ 11 "北京市":['东城区','西城区','崇文区','宣武区','朝阳区','丰台区','石景山区','海淀区','门头沟区','房山区','通州区','顺义区','昌平区','大兴区','怀柔区','平谷区','密云县','延庆县'], 12 "天津市":['和平区', '河东区', '河西区', '南开区', '河北区', '红桥区', '塘沽区', '汉沽区', '大港区', '东丽区', '西青区', '津南区','北辰区', '武清区', '宝坻区', '宁河县', '静海县', '蓟县'], 13 "河北省":['石家庄市','秦皇岛市'], 14 "山西省":['太原市','大同市'], 15 "内蒙古自治区":['呼和浩特市','包头市'] 16 }, 17 "东北地区":{ 18 "辽宁省":["铁岭市","阜新市","朝阳市","沈阳市"], 19 "吉林省":['长春市','吉林市','辽源市'], 20 "黑龙江省":['哈尔滨市','齐齐哈尔市'] 21 }, 22 "华东地区":{ 23 "上海市":["浦东新区","长宁区","宝山区","青浦区"], 24 "江苏省":['南京市','徐州市'], 25 "浙江省":['杭州市','宁波市'], 26 "安徽省":['合肥市','淮南市'], 27 "福建省":['福州市','厦门市'], 28 "江西省":['南昌市','景德镇市'], 29 "山东省":["济南市","青岛市","潍坊市","德州市"] 30 }, 31 } 32 exitFlag = False #设置一个标志位 33 while not exitFlag: 34 Count_1 = 0 # 35 for index,keys in enumerate(CityList.keys()): 36 Count_1 += 1 # 37 print("地区编号:%s\t\t地区名称:%s" % (index,keys)) 38 choice_1 = input("请选择地区编号(q为退出):").strip() 39 if choice_1.isdigit(): 40 choice_1 = int(choice_1) 41 if choice_1 >= 0 and choice_1 < Count_1: 42 key_1 = list(CityList.keys())[choice_1] 43 while not exitFlag: 44 Count_2 = 0 45 for index,keys in enumerate(CityList[key_1]): 46 Count_2 += 1 47 print("省市编号:%s\t\t省市名称:%s" % (index,keys)) 48 choice_2 = input("请选择省市编号(b为返回上级菜单):").strip() 49 if choice_2.isdigit(): 50 choice_2 = int(choice_2) 51 if choice_2 >= 0 and choice_2 < Count_2: 52 key_2 = list(CityList[key_1].keys())[choice_2] 53 while not exitFlag: 54 Count_3 = 0 55 for index,keys in enumerate(CityList[key_1][key_2]): 56 Count_3 += 1 57 print("城市编号:%s\t\t城市名称:%s" % (index,keys)) 58 choice_3 = input("请选择城市编号(b为返回上级菜单,q为退出):").strip() 59 if choice_3.isdigit(): 60 choice_3 = int(choice_3) 61 if choice_3 >= 0 and choice_3 < Count_3: 62 key_3 = list(CityList[key_1][key_2])[choice_3] 63 print("你当前所在的位置:%s\t%s\t%s" % (key_1,key_2,key_3)) 64 print("当前位置为最后一层!系统将返回上一级!") 65 break 66 else: 67 print("你的输入不在指定范围内!") 68 elif choice_3 == 'q': 69 exitFlag = True 70 elif choice_3 == 'b': 71 print("即将返回上级菜单!") 72 break 73 else: 74 print("请输入整数参数!") 75 elif choice_2 == 'b': 76 print("即将返回上级菜单!") 77 break 78 else: 79 print("请输入整数参数!") 80 else: 81 print("你的输入不在指定范围内!") 82 elif choice_1 == 'q': 83 sys.exit(0) 84 else: 85 print("请输入整数参数!")