小练习:三级菜单

要求:

1.运行程序输出第一级菜单

2.选择一级菜单某项,输出二级菜单,同理输出三级菜单

3.输入出错重新选择

4.进入每一层支持返回上一级和退出

5.入最后一层提醒

menu = {
    '001': {
        '011': {
            '111': (1,1,1),
            '211': (2,2,2),
            '311': (3,3,3)
        },
        '021': {
            '121': (4,4,4),
            '211': (5,5,5),
            '311': (6,6,6)
        },
        '031': {
            '131': (7,7,7),
            '231': (8,8,8),
            '331': (9,9,9)
        }
    },
    '002': {
        '012': {
            '112': 'aaa',
            '212': 'bbb',
            '312': 'ccc'
        },
        '022': {
            '122': 'ddd',
            '222': 'eee',
            '322': 'fff'
        },
        '032': {
            '132': 'ggg',
            '232': 'hhh',
            '332': 'iii'
        }
    },
    '003': {
        '013': {
            '113': [1, 1, 1],
            '213': [2, 2, 2],
            '313': [3, 3, 3]
        },
        '023': {
            '123': [4, 4, 4],
            '223': [5, 5, 5],
            '323': [6, 6, 6]
        },
        '033': {
            '133': [7, 7, 7],
            '233': [8, 8, 8],
            '333': [9, 9, 9]
        }
    }
}

current_layer = menu  # 当前所在的菜单层级,类型为字典
layers = []  # 用于放置当前层级的父级,方便返回找回上一层级的key列表
while True:
    print('-------------------------------------------\n')
    print(f"Choice: {', '.join(current_layer.keys())}   【返回/b, 退出/q】")
    choice = input(">>> ").strip()  # 避免错误输入,去除输入字符串前后空格等
    if not choice:
        print("Error: 没有输入!!!")
        continue
    elif choice == 'q':
        exit()
    elif choice == 'b':
        if not layers:  # 规避第一层时,temp中没有存储的父节点
            print("Error: 已经是最外层,无法返回!!!")
            continue
        else:
            current_layer = layers.pop()  # 取出列表最后一个元素,作为父级
    elif choice in current_layer.keys():
        if not isinstance(current_layer[choice], dict):  # 第三层,因为是最后一层,继续往下没有字典结构嵌套,所以需要规避
            print(f"{choice} : {current_layer[choice]}")
            print('Note: 已经第三层了,无法进入下一层级了哦')
            continue
        layers.append(current_layer)
        current_layer = current_layer[choice]
    else:
        print(f"Error: 输入有误,请在列表中选择【返回/b, 退出/q, {' ,'.join(current_layer.keys())}】!!!")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

心灵流浪者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值