python - 从 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()
解决方案
尝试这个。
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()
推荐阅读
- angular - 如何在 fa-icon(角度)上获取 event.target.id?
- reactjs - 使用 Jest 模拟 React 的 AJAX 请求
- ios - Flutter - 在 IOS 上使用 FCM 的后台通知
- delphi - Microsoft OAuth 登录布局错误
- java - 多租户 - 租户的运行时创建
- excel - 如何在 VBA 的列表框中使用值?
- java - 为什么 Java 不能推断超类型?
- bash - 为什么我的 bash 脚本中不断出现语法错误?它是否与“:”有关?
- ios - Swift 5 - 中间视图控制器短暂出现 - 应该删除吗?
- sensors - mipi dsi和spi有什么区别?