首页 > 解决方案 > 从 if 语句中附加 python 字典

问题描述

我正在尝试用 Python 编写一个食谱程序,它接受用户输入并将其附加到一个空字典中,但是每次我运行代码时,字典仍然是空的。请问,怎么了,我该怎么办?

def action():
    answer = input("What would you like to do :- \n"" c.) Create a new recipe \n ""d.) Read all meal recipes \n\n")
    global recipes
    recipes={}
    if answer == "d" :
        print(recipes.values())
    elif answer == "c":
          name =str(input("\nWhat is the name of the food recipe you would like to create ? :- \n"))
          ingredients= str(input('\nWhat are the ingredients required to prepare this meal :- \n'))
          method =str(input('\n How is the meal prepared :- \n'))
          recipes[name]=[name,ingredients,method]
          recipes[name]
action()

标签: pythondictionaryif-statementinputappend

解决方案


尝试这个。

def action():
    global recipes
    recipes ={}
    while True:
        answer = input("What would you like to do :-\n"
                       "a.) Read a meal recipe\n"
                       "b.) Add to a recipe\n"
                       "c.) Create a new recipe\n"
                       "d.) Read all meal recipes\n"
                       "e.) Quit\n\n")

        if answer == "d" :
            print(recipes.values())
        elif answer == "c":
            name =str(input("\nWhat is the name of the food recipe you would like to create ? :- \n"))
            ingredients= str(input("\nWhat are the ingredients required to prepare this meal :- \n"))
            method =str(input('\nHow is the meal prepared :- \n'))
            recipes[name]=[name,ingredients,method]
            print(recipes[name])
        elif answer == "e":
            break
action()

推荐阅读