You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python在if语句内给字典追加元素后仍为空该怎么解决?

问题诊断
  • 核心错误为字典初始化位置错误:你在action()函数内部,每次响应用户操作前都执行了recipes = {}语句,无论之前是否存储过食谱数据,只要调用函数就会把字典重置为空,这是你每次运行都得到空字典的直接原因。
  • 现有代码仅执行一次操作就自动退出,没有循环逻辑支持多次新增、查询操作,新增食谱后无法在同一次程序运行中验证存储结果。
  • 代码末尾的recipes[name]为无意义语句,既不赋值也不打印,不会产生实际作用。
  • 当前数据仅存储在运行内存中,程序关闭后数据会全部丢失,若需要跨运行保留数据需要补充持久化逻辑。
修复代码

基础修复版(单次运行内可多次操作,数据不丢失)

# 把字典初始化移到函数外部,仅在程序启动时执行一次
recipes = {}

def action():
    answer = input("你想要执行什么操作?\n c.) 新建食谱 \n d.) 查看所有食谱 \n q.) 退出程序\n\n")
    global recipes
    if answer == "d":
        if not recipes:
            print("当前暂无存储的食谱")
        else:
            for recipe in recipes.values():
                print(f"\n食谱名称:{recipe[0]}")
                print(f"所需食材:{recipe[1]}")
                print(f"制作方法:{recipe[2]}")
    elif answer == "c":
        name = input("\n请输入要新建的食谱名称:\n")
        ingredients = input('\n请输入该食谱所需的食材:\n')
        method = input('\n请输入该食谱的制作方法:\n')
        recipes[name] = [name, ingredients, method]
        print(f"食谱《{name}》已保存成功")
    elif answer == "q":
        exit()
    else:
        print("输入无效,请重新选择操作")

# 加循环支持多次操作
while True:
    action()

进阶持久化版(重启程序后数据仍保留)

如果需要关闭程序后下次打开还能看到之前存的食谱,可以用json文件存储数据:

import json
import os

# 程序启动时从本地文件读取已有数据
DATA_FILE = "recipes.json"
recipes = {}
if os.path.exists(DATA_FILE):
    with open(DATA_FILE, "r", encoding="utf-8") as f:
        recipes = json.load(f)

def action():
    global recipes
    answer = input("你想要执行什么操作?\n c.) 新建食谱 \n d.) 查看所有食谱 \n q.) 退出程序\n\n")
    if answer == "d":
        if not recipes:
            print("当前暂无存储的食谱")
        else:
            for recipe in recipes.values():
                print(f"\n食谱名称:{recipe[0]}")
                print(f"所需食材:{recipe[1]}")
                print(f"制作方法:{recipe[2]}")
    elif answer == "c":
        name = input("\n请输入要新建的食谱名称:\n")
        ingredients = input('\n请输入该食谱所需的食材:\n')
        method = input('\n请输入该食谱的制作方法:\n')
        recipes[name] = [name, ingredients, method]
        # 新增后立即写入本地文件
        with open(DATA_FILE, "w", encoding="utf-8") as f:
            json.dump(recipes, f, ensure_ascii=False, indent=2)
        print(f"食谱《{name}》已保存成功")
    elif answer == "q":
        exit()
    else:
        print("输入无效,请重新选择操作")

while True:
    action()

内容的提问来源于stack exchange,提问作者Ibrahim Ayoola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 12:24:01