python--多级菜单(多级登录)

1、简单繁多版(未优化之前):

#__author:  liangchen     Date:   2019/8/15
menu = {
        "江西":{
            "南昌":{
                "南昌西站":{},
                "东湖区":{}
            },
            "吉安":{
                "永丰":{},
                "吉水":{}
            },
},
        "上海":{
            "嘉定":{
                "城区":{},
                "嘉定新城":{}
            },
            "徐汇":{
                "复旦大学":{},
                "徐家汇站":{}
            }
        },
        "广东":{
            "东莞":{
                "东莞站":{},
                "白石山":{}
            },
            "惠州":{
                "惠州站":{},
                "人字冈":{}
            }
        }
        }
flag = True
while True and flag:
    for i in  menu:
        print(i)
    select1 = input("请选择地点(退出:q):").strip()
    if select1 == 'q':
        flag = False
    while True and flag:    #使程序在第二层循环
        if select1 in menu:
            for i in menu[select1]:
                print(i)
            select2 = input("请选择地点(返回上一层:b,退出:q):").strip()
            if select2 == 'b':
                break
            if select2 == 'q':
                flag = False
            while True and flag:        #使程序在第三层循环
                if select2 in menu[select1]:
                    for i in menu[select1][select2]:
                        print(i)
                    select3 = input("请选择地点(返回上一层:b,退出:q):").strip()
                    if select3 in menu[select1][select2]:
                        print("welcome you come to %s!"%select3)
                    if select3 == 'b':
                        break
                    if select3 == 'q':
                        flag = False

2、简易优化版

#__author:  liangchen     Date:   2019/8/15
menu = {
        "江西":{
            "南昌":{
                "南昌西站":{},
                "东湖区":{}
            },
            "吉安":{
                "永丰":{},
                "吉水":{}
            },
},
        "上海":{
            "嘉定":{
                "城区":{},
                "嘉定新城":{}
            },
            "徐汇":{
                "复旦大学":{},
                "徐家汇站":{}
            }
        },
        "广东":{
            "东莞":{
                "东莞站":{},
                "白石山":{}
            },
            "惠州":{
                "惠州站":{},
                "人字冈":{}
            }
        }
        }
current_layer = menu
parent_layers = []      #存放父级菜单
while True:
    for key in current_layer:
        print(key)
    select = input(">>>>").strip()
    if select in current_layer:
        parent_layers.append(current_layer)  #追加父级菜单
        current_layer = current_layer[select]
    elif select == "b":
        if parent_layers:
            current_layer = parent_layers.pop()

  

posted @ 2019-08-15 16:56  BruceTyler  阅读(261)  评论(0编辑  收藏  举报