城市3级列表最终版

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# by wk

'''
用户交互,显示省市县三级联动的选择
要求:用户输入河北,则打印河北省下的市,用户输入市,则显示该河北省的这个市下的县
dic = {
    "河北": {
        "石家庄": ["鹿泉", "藁城", "元氏"],
        "邯郸": ["永年", "涉县", "磁县"],
    }
    "河南": {
        ...
    }
    "山西": {
        ...
    }
'''


# import sys

# 取出省市列表
def provinces_dict():
    my_city_dict = {
        "河北": {
            "石家庄": ["鹿泉", "藁城", "元氏"],
            "邯郸": ["永年", "涉县", "磁县"],
            "唐山": ["玉田县", "乐亭县", "迁西县"],
        },
        "江苏": {
            "南京": ["溧水", "高淳", "玄武"],
            "苏州": ["平江", "虎丘", "虞山"],
            "无锡": ["崇安", "南长", "北塘"],
        },
        "山西": {
            "太原": ["清徐县", "阳曲县", "娄烦县"],
            "大同": ["天镇县", "阳高县", "广灵县"],
            "朔州": ["怀仁", "右玉", "山阴"],
        }
    }
    return my_city_dict


# 省列表并输入被选择的省
def choose_provinces(provinces_list):
    for provinces in provinces_list:
        print(provinces)
    my_provinces = input('请输入省的名称: ')
    return my_provinces


# 传入省字典,展示城市列表并输入被选择的城市
def choose_city(my_city, my_provinces):
    for area in my_city[my_provinces]:
        print(area)
    my_area = input('请输入城市的名称,返回上一级请按(B or b): ')
    return my_area


# 传入省,市字典,展示县
def choose_location(my_city, choose_city, choose_area):
    for mylocation in my_city[choose_city][choose_area]:
        print(mylocation)


def main():
    flag = True
    while flag:
        flag_provinces = True
        my_provinces_dict = provinces_dict()
        while flag_provinces:
            flag_city = True
            my_provinces = choose_provinces(my_provinces_dict)
            if my_provinces not in my_provinces_dict:
                print('您输入的信息有误,请重新输入!')  # 如果输入的数据不在菜单里,需要重新输入
                flag_city = False
            while flag_city:
                flag_location = True
                my_city = choose_city(my_provinces_dict, my_provinces)
                if my_city == 'B' or my_city == 'b':  # 判断如果选择了B或者b返回上级菜单
                    flag_location = False  # 退出本层循环
                    flag_city = False  # 退出上层层循环
                elif my_city not in my_provinces_dict[my_provinces]:
                    print('您输入的信息有误,请重新输入!')  # 如果输入的数据不在菜单里,需要重新输入
                    flag_location = False  # 退出本层循环
                while flag_location:
                    choose_location(my_provinces_dict, my_provinces, my_city)
                    # if my_location not in my_provinces_dict[my_provinces][my_city]:
                    #     flag_location = True
                    flag_location = False  # 退出
                    flag_city = False
                    flag_provinces = False
                    flag = False


if __name__ == '__main__':
    main()

 

posted @ 2017-07-27 16:35  GodSpeed034  阅读(216)  评论(0编辑  收藏  举报