python 多级菜单 纯循环与分支

python 多级菜单 纯循环与分支

源代码:

#!/usr/bin/python3

__author__ = 'beimenchuixue'
__blog__ = 'http://www.cnblogs.com/2bjiujiu/' def menu(message):
print('按q返回上一层')
print('按e退出')
ec = 'q' # 返回上一级
ex = 'e'
for i in message: # 打印一级菜单
print(i)
while True: # 进入一级菜单选择
choice1 = input('请输入1>>>:')
if choice1 in message: # 判断是否在字典中
for i1 in message[choice1]:
print(i1) # 打印值 while True:
choice2 = input('请输入2>>>:') # 进入二级菜单选择
if choice2 in message[choice1]:
for i2 in message[choice1][choice2]:
print(i2) while True:
choice3 = input('请输入3>>>:') # 进入三级菜单选择
if choice3 in message[choice1][choice2]:
for i3 in message[choice1][choice2][choice3]:
print(i3) elif choice3 == ec: # 返回判断
for i2 in message[choice1]:
print(i2) # 打印上一级菜单
break elif choice3 == ex: # 退出判断
exit('退出中……ing')
else:
print('输入错误,请重新输入,么么哒') elif choice2 == ec: # 返回判断,并打印上一级菜单
for i1 in message:
print(i1)
break
elif choice2 == ex: # 退出判断
exit('退出中……ing')
else:
print('输入错误,请重新输入,么么哒') elif choice1 == ec: # 返回判断
print('已经最*菜单,完全退出请输入 e ')
continue
elif choice1 == ex: # 退出判断
exit('退出中……ing')
else:
print('输入错误,请重新输入,么么哒') if __name__ == '__main__':
message = {'湖南':
{'衡阳':
{'珠晖区': '湖南工学院'},
'湘潭':
{'晖晖': '啦啦'}},
'北京':
{'朝阳':
{"德玛:北京大学"}}}
menu(message)
坑点:
1.纯分支与循坏,重复代码
2.多级字典的访问几级就需要几个[]中括号 用面向过程,函数方式做,返回上一级菜单未做,可做一个参考,有更好思路再更新
#!/usr/bin/python3

def menu_to(message):
'''打印菜单'''
try:
message.endswith('end')
except:
for i in message:
print(i)
else:
print(message.replace('end', '')) def get_message_key(message_info):
'''获得每层字典的单边值'''
try:
keys = []
for i in message_info:
message_info[i]
keys.append(i)
return keys
except:
return message_info + 'end' def menu_go(message_info):
'''进入主菜单'''
while True:
try:
judgment(message_info)
except Exception as e:
print(e) def judgment(message_info):
'''循环菜单'''
keys = get_message_key(message_info)
while True:
menu_to(keys) choice = input('请输入>>>:')
if choice == ec:
print('暂时未实现')
return judgment(message_info)
elif choice == ex:
exit('退出程序') if type(keys) == type('str') and keys.endswith('end'):
print('菜单到底了')
continue
else: if choice in keys:
message_info = message_info[choice]
return judgment(message_info)
else:
print('输入错误,请重新输入') if __name__ == '__main__':
info_message = {'湖南':
{'衡阳':
{'珠晖区': '湖南工学院'},
'湘潭':
{'晖晖': '啦啦'}},
'北京':
{'朝阳':
{"德玛": "北京大学"}}}
ec = 'q' # 返回上一级
ex = 'e' # 退出程序
menu_go(info_message)

  

 
上一篇:Mac下finder中无法关闭的小条


下一篇:iOS开发中的错误整理,百思项目'我的'模块,tableFooterViewHeight的问题.提醒自己对KVO和Block的运用欠缺