首页 > 代码库 > python三级菜单

python三级菜单

#__author: Tiger li
#date: 2016/8/24

province={
    "河北省":{
        "石家庄市":[‘长安区‘,‘桥西区‘,‘新华区‘],
        "唐山市":[‘路北区‘,‘路南区‘,‘古冶区‘],
        "保定市":[‘竞秀区‘,‘莲池区‘,‘满城区‘]
        },
    "吉林省":{
        "长春市":[‘南关区‘,‘朝阳区‘,‘绿园区‘],
        "吉林市":[‘船营区‘,‘龙潭区‘,‘昌邑区‘],
        "松原市":[‘宁江区‘,‘乾安县‘,‘长岭县‘]
        },
    "黑龙江省":{
        "哈尔滨市":[‘道里区‘,‘南岗区‘,‘道外区‘],
        "佳木斯市":[‘向阳区‘,‘前进区‘,‘东风区‘],
        "牡丹江市":[‘东安区‘,‘阳明区‘,‘爱民区‘]
        }
}

while True:
    for pro in province:
        print(pro)
    pro_input = input("请输入省份(例:吉林省) 退出(e): ")
    if pro_input in province.keys():
        citylist = province[pro_input]
        while True:
            for city in citylist:
                print (city)
            city_input = input("请输入城市(例:吉林市) 返回上一层(q) 退出(e): ")
            if city_input in citylist.keys():
                while True:
                    for area in citylist[city_input]:
                        print(area)
                    area_input = input("返回上一层(q) 退出(e): ")
                    if area_input == ‘q‘:
                        break
                    elif area_input == ‘e‘:
                        exit()
                    else:
                        print(‘输入错误,请重新输入: ‘)
            elif city_input == ‘q‘:
                print(‘返回上一层菜单‘)
                break
            elif city_input == ‘e‘:
                exit()
            else:
                print(‘输入错误,请重新输入: ‘)
    elif pro_input == ‘e‘:
        exit()
    else:
        print(‘输入错误,请重新输入: ‘)

 

好的程序员都会写出非常优质的代码,什么是优质的代码呢?你用30行代码实现的东西,人家只需要10行,这就是差别。同样,三级菜单还有一套更精简的代码,就叫高大上版吧

#__author: Tiger li
#date: 2016/8/25
menu={
    "河北省":{
        "石家庄市":[‘长安区‘,‘桥西区‘,‘新华区‘],
        "唐山市":[‘路北区‘,‘路南区‘,‘古冶区‘],
        "保定市":[‘竞秀区‘,‘莲池区‘,‘满城区‘]
        },
    "吉林省":{
        "长春市":[‘南关区‘,‘朝阳区‘,‘绿园区‘],
        "吉林市":[‘船营区‘,‘龙潭区‘,‘昌邑区‘],
        "松原市":[‘宁江区‘,‘乾安县‘,‘长岭县‘]
        },
    "黑龙江省":{
        "哈尔滨市":[‘道里区‘,‘南岗区‘,‘道外区‘],
        "佳木斯市":[‘向阳区‘,‘前进区‘,‘东风区‘],
        "牡丹江市":[‘东安区‘,‘阳明区‘,‘爱民区‘]
        }
}

current_layer = menu #实现动态循环

parent_layers = [] #保存所有父级,最后一个元素永远都是父级
while True:
    for key in current_layer:
        print(key)
    choice = input(">>>:").strip()
    if len(choice) == 0:continue
    if choice in current_layer:
        parent_layers.append(current_layer) #在进入下一层之前,把当前层(即下一层的父级)
        #下一次循环,当用户选择b的时候,就可以直接取列表的最后一个值出来就ok了
        current_layer = current_layer[choice] #改成了子层
    elif choice == "b":
        if parent_layers: # []
            current_layer = parent_layers.pop() #取出列表的最后一个值,因为它就是当前层的父级
    else:
        print("输入错误,请重新输入:")

python三级菜单