目錄
-
一、Python進階實戰(zhàn)之三級菜單
- 1.1 面條版
- 1.2 文藝青年版
一、Python進階實戰(zhàn)之三級菜單
-
打印省、市、縣三級菜單
-
可返回上一級
-
可隨時退出程序
1.1 面條版
menu = {
'北京': {
'海淀': {
'五道口': {
'soho': {},
'網(wǎng)易': {},
'google': {}
},
'中關(guān)村': {
'愛奇藝': {},
'汽車之家': {},
'youku': {},
},
'上地': {
'百度': {},
},
},
'昌平': {
'沙河': {
'老男孩': {},
'北航': {},
},
'天通苑': {},
'回龍觀': {},
},
'朝陽': {},
'東城': {},
},
'上海': {
'閔行': {
"人民廣場": {
'炸雞店': {}
}
},
'閘北': {
'火車戰(zhàn)': {
'攜程': {}
}
},
'浦東': {},
},
'山東': {},
}
tag = True
while tag:
menu1 = menu
for key in menu1: # 打印第一層
print(key)
choice1 = input('第一層>>: ').strip() # 選擇第一層
if choice1 == 'b': # 輸入b,則返回上一級
break
if choice1 == 'q': # 輸入q,則退出整體
tag = False
continue
if choice1 not in menu1: # 輸入內(nèi)容不在menu1內(nèi),則繼續(xù)輸入
continue
while tag:
menu_2 = menu1[choice1] # 拿到choice1對應(yīng)的一層字典
for key in menu_2:
print(key)
choice2 = input('第二層>>: ').strip()
if choice2 == 'b':
break
if choice2 == 'q':
tag = False
continue
if choice2 not in menu_2:
continue
while tag:
menu_3 = menu_2[choice2]
for key in menu_3:
print(key)
choice3 = input('第三層>>: ').strip()
if choice3 == 'b':
break
if choice3 == 'q':
tag = False
continue
if choice3 not in menu_3:
continue
while tag:
menu_4 = menu_3[choice3]
for key in menu_4:
print(key)
choice4 = input('第四層>>: ').strip()
if choice4 == 'b':
break
if choice4 == 'q':
tag = False
continue
if choice4 not in menu_4:
continue
# 第四層內(nèi)沒數(shù)據(jù)了,無需進入下一層
北京
上海
山東
第一層>>: 背景
北京
上海
山東
第一層>>: 北京
海淀
昌平
朝陽
東城
第二層>>: 海淀
五道口
中關(guān)村
上地
第三層>>: 中關(guān)村
愛奇藝
汽車之家
youku
第四層>>: q
1.2 文藝青年版
menu = {
'北京': {
'海淀': {
'五道口': {
'soho': {},
'網(wǎng)易': {},
'google': {}
},
'中關(guān)村': {
'愛奇藝': {},
'汽車之家': {},
'youku': {},
},
'上地': {
'百度': {},
},
},
'昌平': {
'沙河': {
'老男孩': {},
'北航': {},
},
'天通苑': {},
'回龍觀': {},
},
'朝陽': {},
'東城': {},
},
'上海': {
'閔行': {
"人民廣場": {
'炸雞店': {}
}
},
'閘北': {
'火車戰(zhàn)': {
'攜程': {}
}
},
'浦東': {},
},
'山東': {},
}
# part1(初步實現(xiàn)):能夠一層一層進入
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: 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])
北京
上海
山東
>>: 上海
閔行
閘北
浦東
>>: 浦東
>>: q
北京
上海
山東
>>: q
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
