python3之利用字典和列表实现城市多级菜单
利用字典和列表实现城市多级菜单
1 #coding:utf-8 2 #利用字典和列表实现城市多级菜单 3 addrIndex = {"1":"北京","2":"上海","3":"南京","4":"福建"} 4 addrDict = {"北京":["东城区","西城区","大兴区"],"上海":["黄浦区","长宁区","宝山区"],"南京":["玄武区","秦淮区","六合区"],"福建":["龙岩","泉州"]} 5 while True: 6 i = 1 7 #循环打印城市名称 8 for cs in addrDict.keys(): 9 print("%d.%s" %(i,cs)) 10 i += 1 11 choIndex = input("请输入你城市编号:") 12 13 #为每个城市指定编号值,便于判断输入错误和扩展 14 if choIndex not in addrIndex.keys(): 15 print("输入有误!") 16 continue 17 # print(addrDict[addrIndex[choIndex]]) 18 19 while True: 20 i = 1 21 #根据输入的城市编号,获取城市名称,城市名称直接为addrDict字典的key 22 for pq in addrDict[addrIndex[choIndex]]: 23 print("%d.%s" %(i,pq)) 24 i += 1 25 pqCho = input("请输入片区编号,输入q返回上级:") 26 27 #输入q跳出 28 if pqCho == "q": 29 break 30 #输入正确的值打印,pqCho.isdigit()用于判断输入非q字符串错误 31 elif pqCho.isdigit() and (int)(pqCho)-1>=0 and (int)(pqCho)-1<=len(addrDict[addrIndex[choIndex]])-1: 32 print("你选择的是:%s" %(addrDict[addrIndex[choIndex]][(int)(pqCho)-1])) 33 else: 34 print("输入有误!") 35 continue