新手:python里面while循环2——代码优化

上一笔记里面,有大量重复的代码,这次来进行优化,如果有其他方法,请教教我,respect!

点击查看代码
# -*- coding:utf-8 -*-
# __author: Andy Liu
# Date: 2023/3/2

menu = {
    "lucky_shop": {
        "fruit": {
            "banana": {"banana need 8yuan": {"This is the last layer, please return": {None}}},
            "apple": {"apple need 7yuan": {"This is the last layer, please return": {None}}},
            "tangerine": {
                "Sugar Tachibana need 5yuan": {"This is the last layer, please return": {None}},
                "Citrus need 8yuan": {"This is the last layer, please return": {None}}

            }
        },
        "stationery": {
            "pencil": {"pencil need 2yuan": {"This is the last layer, please return": {None}}},
            "pen": {"pen need 5yuan": {"This is the last layer, please return": {None}}},
            "notebook": {
                "small need 1yuan": {"This is the last layer, please return": {None}},
                "middle need 2yuan": {"This is the last layer, please return": {None}},
                "big need 3yuan": {"This is the last layer, please return": {None}}
            }
        },
        "kitchen": {
            "knife": {"knife need 10yuna": {"This is the last layer, please return": {None}}},
            "wok": {
                "middle need 20yuan": {"This is the last layer, please return": {None}},
                "big need 25yuan": {"This is the last layer, please return": {None}}
            },
            "spatula": {"spatula need 13yuan": {"This is the last layer, please return": {None}}}
        }
    },
    "seven_eleven": {None},
    "super_market": {None}
}

quit_flag = False
current_layer = menu
layer_records = []

while not quit_flag:
    print("[press 'b' return to the previous layer.]")
    print("[press 'q' to exit.]")
    while not quit_flag:
        print("-----------")
        for key in current_layer:
            print(key)
        choice = input(">> ").strip()
        if choice in current_layer:
            layer_records.append(current_layer)  # record the current layer
            current_layer = current_layer[choice]  # assign the next layer to the current_layer
        elif choice == "b":
            if layer_records:
                # remove the last record of the list and assign it to the current_layer
                current_layer = layer_records.pop()
        elif choice == "q":
            quit_flag = True
        else:
            print("invalid input!")

print("Welcome again!")

posted @ 2023-03-02 12:45  羊羊羊01  阅读(19)  评论(0)    收藏  举报