#要求:
打印省、市、县三级菜单
可返回上一级
可随时退出程序
#!/usr/bin/python #_*_coding:utf-8_*_ map_menu = { '河北省':{ '石家庄市':['长安区','桥西区','新华区','裕华区','井陉矿区','藁城区','鹿泉区','栾城区','赵县','平山县'], '沧州市':['泊头市','南皮市','任丘市','青县','新华区','运河区','高新区','渤海新区','黄骅','河间','献县'], '唐山市':['路南区','路北区','丰南区','开平区','丰润区','遵化市','迁安市','迁西县','玉田县'] }, '广东省':{ '广州市':['荔湾区','越秀区','海珠区','天河区','白云区','黄埔区','番禺区','花都区','增城区','从化区'], '深圳市':['罗湖区','福田区','南山区','宝安区','龙岗区','盐田区','光明新区','深汕区','坪山区','龙华区'], '珠海市':['香洲区','斗门区','金湾区','拱北区'] }, '北京省':{ '北京市':['东城区','西城区','朝阳区','海淀区','丰台区','昌平区','石景山区','大兴区','怀柔区','通州区','顺义区'] }, '辽宁省':{ '沈阳市':['和平区','沈河区','大东区','皇姑区','铁西区','苏家屯区','东陵区','沈北新区','于洪区','康平县'], '大连市':['中山区','西岗区','沙河口区','甘井子区','旅顺口区','金州区','瓦房店市','庄河市','长海县'], '鞍山市':['铁东区','铁西区','立山区','千山区','海城市','台安县','岫岩满族自治县'] }, '湖南省':{ '长沙市':['岳麓区','芙蓉区','天心区','开福区','雨花区','望城区','长沙县','浏阳市','宁乡市'], '株洲市':['天元区','荷塘区','芦淞区','石峰区','醴陵市','株洲县','炎陵县','茶陵县','攸县'], '湘潭市':['岳塘区','雨湖区','湘乡市','韶山市','湘潭县'] } } # 打印省份列表 province_name_list = list(map_menu.keys()) while True: print("Province List".center(40, '-')) # 打印省份列表 for name in province_name_list: print(province_name_list.index(name)+1,name) # 选择需要的省份 province_id = input('请输入与省份对应的编号,输入q退出程序. >>: ').strip() # 选择省份序号的规则制定,不符合则告知输入对应的序号 if province_id.isdigit(): province_id = int(province_id) if province_id > 0 and province_id <= len(province_name_list): #根据省ID,获取对应省的名称 province_name = province_name_list[province_id - 1] print(province_name) # 根据省名称,获取对应的市列表 city_name_list = list(map_menu[province_name].keys()) while True: print("City List".center(40, '-')) # 打印市列表 for city_name in city_name_list: print(city_name_list.index(city_name)+1,city_name) city_id = input('请输入与市对应的编号,输入b返回上级菜单,输入q退出程序! >>: ').strip() if city_id.isdigit(): city_id = int(city_id) # 判断输入city_id的内容 if city_id > 0 and city_id <= len(city_name_list): # 根据市ID,获取市的名称 city_name = city_name_list[city_id - 1] print(city_name) # 获取县(区)的列表 county_name_list = map_menu[province_name][city_name] while True: print('County List'.center(40,'-')) # 打印县(区)列表 for county_name in county_name_list: print(county_name_list.index(county_name)+1,county_name) signal = input('输入b返回上一级菜单,输入q退出程序!>>: ').strip() if signal == 'b': break elif signal == 'q': exit() else: print('您输入的%s不存在,b返回上一级,q退出程序!' %signal) else: print('您输入的%s编号不存在,请输入与城市对应的编号!' %city_id) elif city_id == 'b': break elif city_id == 'q': exit() else: print('您输入的%s编号不存在,请输入与省对应的编号!' %province_id) elif province_id == 'q': exit() else: print('输入不合法,请重新输入!')