python三级项目_python 三级菜单

三级列表:

menu = {

'北京':{

'海淀':{

'五道口':{

'soho':{},

'网易':{},

'google':{}

},

'中关村':{

'爱奇艺':{},

'汽车之家':{},

'youku':{},

},

'上地':{

'百度':{},

},

},

'昌平':{

'沙河':{

'地铁':{},

'北航':{},

},

'天通苑':{},

'回龙观':{},

},

'朝阳':{},

'东城':{},

},

'上海':{

'闵行':{

"人民广场":{

'炸鸡店':{}

}

},

'闸北':{

'火车站':{

'携程':{}

}

},

}

基础版本:

#首先要有个死循环,能够一直的输入

while True:

#打印第一层的数据

for key in menu:

print(key)

#然后叫用户选择

choice = input(">>:").strip()#去掉空格

#判断是否是回车

if choice == 'b':break

if choice == 'q':exit("欢迎下次再来")

if len(choice) ==0:continue#避免输入空格

print("------进入下一级------".center(50))

#第一,确保北京在字典里,有一个key,有,直接调这个key,进入下一级

#判断字典有没有这个值,有get和in两种方法

if choice not in menu:continue#如果不在里面继续往里输,跳过这次选择

#为下一层循环单独加一个循环

while True:

#先把下一层取到

for key2 in menu[choice]:

print(key2)

choice2 = input(">>:").strip()

if choice2 == 'b': break

if choice2 == 'q': exit("欢迎下次再来{name}".format(name=choice2))

if len(choice2) ==0:continue

if choice2 not in menu[choice]:continue#判断用户输入的选项如果没在第这层菜单中,跳出

# 为下一层循环单独加一个循环

while True:

# 先把下一层取到

for key3 in menu[choice][choice2]:

print(key3)

choice3 = input(">>:").strip()

if choice3 == 'b': break

if choice3 == 'q': exit("欢迎下次再来")

if len(choice3) == 0: continue

if choice3 not in menu[choice][choice2]: continue # 判断用户输入的选项如果没在第这层菜单中,跳出

while True:

# 先把下一层取到

for key4 in menu[choice][choice2][choice3]:

print(key4)

choice4 = input(">>:").strip()

if choice4 == 'b': break

if choice4 == 'q': exit("欢迎下次再来")

if len(choice4) == 0: continue

if choice4 not in menu[choice][choice2][choice3]: continue # 判断用户输入的选项如果没在第这层菜单中,跳出

优化之后,高级版本:

current_level = menu #当前层 #初始变量

last_level = [] #定义空列表,返回上一级用的,每进入一层就存一层

while True:

for key in current_level:#循环每一层

print(key)

choice = input(">>:").strip()

if len(choice) == 0:continue

# 返回上一层

# 自己记住每层的上一层,每次在进入下一层之前,我当前层就相当于下一层的父集

if choice == 'b':

# current_level = last_level#把当前层的变量改成上一层[把当前层改成父亲层,这样下一次循环就回到上一层]

if not last_level :break #if len(last_level) == 0:break

current_level = last_level[-1]#每退出一层取列表最后一个值

last_level.pop()#删一层

if choice not in current_level:continue

#choice在里面进入下一层

last_level.append(current_level)#每进一层存一层

current_level = current_level[choice]#给current_level重新赋值,进入下一层,每换一个变量,下一次就到了for key in current_level层

完毕。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值