Python进阶实战之三级菜单
一、Python进阶实战之三级菜单
- 打印省、市、县三级菜单
- 可返回上一级
- 可随时退出程序
menu = {
'北京': {
'海淀': {
'五道口': {
'soho': {},
'网易': {},
'google': {}
},
'中关村': {
'爱奇艺': {},
'汽车之家': {},
'youku': {},
},
'上地': {
'百度': {},
},
},
'昌平': {
'沙河': {
'老男孩': {},
'北航': {},
},
'天通苑': {},
'回龙观': {},
},
'朝阳': {},
'东城': {},
},
'上海': {
'闵行': {
"人民广场": {
'炸鸡店': {}
}
},
'闸北': {
'火车战': {
'携程': {}
}
},
'浦东': {},
},
'山东': {},
}
# part1(初步实现):能够一层一层进入
layers = [
menu,
]
while True:
current_layer = layers[-1]
#遍历当前层级,打印所有选项
for key in current_layer:
print(key)
#与用户交互,并去除左右空白
choice = input('>>:').strip()
if choice == 'q': #直接退出
break
if choice not in current_layer: #输入内容不在当前层级内,继续输入
continue
layers.append(current_layer[choice]) #进入下一层
# part2(改进):加上退出机制
layers = [
menu,
]
while True:
if len(layers) == 0: #如果为空列表,退出(当在顶层按b时,栈被清空,循环终止。)
break
current_layer = layers[-1]
for key in current_layer:
print(key)
choice = input('>>:').strip()
if choice == 'b': #选择返回上层
layers.pop(-1) #弹出栈顶元素(返回到上一层)
continue
if choice == 'q':
break
if choice not in current_layer:
continue
layers.append(current_layer[choice])

浙公网安备 33010602011771号