python3 练习题(多级菜单)

'''
多级菜单
需求:
1.现有省/市/县3级结构,要求程序启动后,允许用户可依次选择进入各子菜单
2.可在任意一级菜单返回上一级
3.可以在任意一级菜单退出程序
所需新知识点: 列表/字典
'''
menu = {
    "山东": {
        "济南": {
              "平阴": {},
              "商河": {},
              "莱芜": {}
         },
        "济宁": {
              "金乡": {},
              "微山": {},
              "嘉祥": {}
        },
        "曲阜": {
              "南辛": {},
              "陵城": {},
              "防山": {}
        }
    },
    "北京": {
        "海淀": {
                "万寿路": {},
                "永定路": {},
                "中关村": {}
       },
        "昌平": {
                "回龙观": {},
                "南口": {},
                "沙河": {}
        },
        "朝阳": {
                "呼家楼": {},
                "三里屯": {},
                "双井": {}
        }
    },
    "上海": {
        "黄浦": {
                "南京东路": {},
                "外滩": {},
                "瑞金二路": {}
        },
        "徐汇": {
            "湖南路": {},
            "天平路": {},
            "枫林路": {}

        },
        "长宁": {
                "华阳路": {},
                "新华路": {},
                "江苏路": {}
        }
    },
}

current_menu = menu
layers = []
while True:
    for i in current_menu:
        print(i)
    choice = input(">: ").strip()
    if choice in current_menu:
        layers.append(current_menu)
        current_menu = current_menu[choice]
    elif choice.upper() == "B":
        if len(layers) == 0:
            print("已经到顶了")
            continue
        current_menu = layers.pop()

----------------------------------------------微调1------------------------------------

current_menu = menu
choices = []
while True:
    for i in current_menu:
        print(i)
    choice = input(">: ").strip()
    if choice in current_menu:
        choices.append(choice)
        current_menu = current_menu[choice]
    elif choice.upper() == "B":
        current_menu = menu
        if len(choices) == 0:
            print("已经到顶了")
            continue
        choices.pop()
        for i in choices:
            current_menu = current_menu[i]
'''
比上面的代码多了最后两行,请大佬留言,哪个方式更好一些.
'''

------------------------------------------微调2---------------------------------------

current_menu = menu
choices = []
while True:
    for i in current_menu:
        print(i)
    print("q退出 b返回上一级")
    if len(choices) >= 1:
        choice = input("%s>: " % '>'.join(choices)).strip()
    else:
        choice = input(">: ").strip()
    if choice in current_menu:
        choices.append(choice)
        current_menu = current_menu[choice]
    elif choice.upper() == "B":
        current_menu = menu
        if len(choices) == 0:
            print("已经到顶了")
            continue
        choices.pop()
        for j in choices:
            current_menu = current_menu[j]
    elif choice.upper() == "B":
        break 

 

 

posted on 2019-04-10 10:14  lilyxiaoyy  阅读(309)  评论(0编辑  收藏  举报

返回
顶部