要求:
- 现有省,市,县三级结构,要求程序启动后,允许用户可依次选择进入各级子菜单。
- 可在任意一级菜单返回上级菜单。
- 可在任意一级退出菜单。
# 设置简单的三级菜单
menu = {
'北京':{
'东城':{
'沙河':['沙河机场', '链家'],
'天通苑':['北方明珠', '天通尾货']
},
'朝阳':{
'花家地': ['朝阳公园', '望京soho'],
'北小河':['北小河公园', '北京中学']
}
},
'上海':{
'虹桥':{
'虹桥机场':['超市', '特产店', '水吧'],
'东方明珠':['电影院', '游泳馆', '餐馆']
},
'浦东':{
'静秀路':['世纪公园', '立交桥'],
'中环路':['鲁迅公园', '同济大学']
}
},
'河北':{
'石家庄':{
'行唐': ['东正', '阳关'],
'赵县': ['赵州桥', '高阳村']
},
'唐山':{
'滦南县': ['司各庄镇', '安各庄镇'],
'玉田县': ['玉田镇', '连家店镇']
}
}
}
province_list = list(menu.keys()) # 把字典的key转化为列表
while True:
print('--------省级菜单--------')
for p in province_list:
print(province_list.index(p) + 1, p) # 打印省级菜单
choice_pro = input('请输入编号或者输入q(quit)退出: ')
if choice_pro.isdigit():
choice_pro = int (choice_pro)
if choice_pro>0 and choice_pro<=len(province_list):
province_name = province_list[choice_pro-1] # 获取省名
city_list = list(menu[province_name].keys()) # 获取省名字典中的城市菜单
# 市级菜单
while True:
print('--------市级菜单--------')
for c in city_list:
print(city_list.index(c)+1, c) # 输出市级菜单
choice_city = input('请输入编号或者输入q(quit)退出或者b(back)返回上级菜单: ')
if choice_city.isdigit():
choice_city = int(choice_city)
if choice_city>0 and choice_city<=len(city_list):
city_name = city_list[choice_city-1] #获取市名
town_list = list(menu[province_name][city_name]) #获取对应市名中的县级菜单
# 县级菜单
while True:
print('--------县级菜单--------')
for t in town_list:
print(town_list.index(t)+1, t) # 打印县级菜单
town_choice = input('请输入q(quit)退出或者b(back)返回上级菜单: ')
if town_choice == 'b':
break
elif town_choice == 'q':
exit()
else:
print('输入错误! ')
else:
print('没有此选项! ')
elif choice_city == 'b':
break
elif choice_city == 'q':
exit()
else:
print('输入错误! ')
else:
print('没有此选项! ')
elif choice_pro == 'q':
exit()
else:
print('输入错误! ')