获取配方中的配料成本

2024-04-28 04:34:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个简短的程序来计算配方中成分的成本。我已经创建了一个包含名称、购买数量、购买价格和用于计算成本的单位的列表。我有一个函数来计算每种成分的单独成本,该成本应传递给主函数,主函数将打印一份声明,显示成分名称和配方中使用的单位数量的成本。 我的问题是,当我打印报表时,它没有获取正确的信息

    compute_ingredient_cost(recipe_ingredients)
    unit_qty = 0
    for item in recipe_ingredients:
        print(f"The cost of {item[0]} is ${item[2]:.2f} for {unit_qty} units.")
    print()

def compute_ingredient_cost(recipe_ingredients):
    ingredient_cost =[]
    for item in recipe_ingredients:
        unit_qty = input(f"Enter the qty of {item[0]} used: ")
        ingredient_cost = float(COST) / float(QTY) * float(unit_qty)
        item.append(ingredient_cost)
    print()
    return ingredient_cost

当我运行程序时,我得到的是:

Enter the qty of ing1 used: 25
Enter the qty of ing2 used: 20
Enter the qty of ing3 used: 15
Enter the qty of ing4 used: 10

The cost of ing1 is $6.25 for 0 units.
The cost of ing2 is $6.25 for 0 units.
The cost of ing3 is $7.25 for 0 units.
The cost of ing4 is $3.50 for 0 units.

它显示的是原料的总购买价格,而不是所用原料的成本,所用单位显示为0。有人能告诉我怎么解决这个问题吗?求你了


Tags: oftheforisrecipeitemused成本
1条回答
网友
1楼 · 发布于 2024-04-28 04:34:28

我试图解决您的问题,并得出以下代码:

ingridients = [{"name": "ing1", "qty_purchased": 10, "purchase_price": 100},
                {"name": "ing2", "qty_purchased": 20, "purchase_price": 100},
                {"name": "ing3", "qty_purchased": 30, "purchase_price": 90},
                {"name": "ing4", "qty_purchased": 40, "purchase_price": 40}]

for item in ingridients:
    print(item)
    
print()

def compute_ingr_cost(recipe_ingr):
    ingr_used = []
    for item in recipe_ingr:
        unit_qty = input(f"Enter the qty of {item['name']} used: ")
        ingr_cost = float(item['purchase_price']) / float(item['qty_purchased']) * float(unit_qty)
        ingr_used.append({"name": item['name'], "ingredient_cost": ingr_cost, "ingredient_qty": unit_qty})
    return(ingr_used)

ingr_used = compute_ingr_cost(ingridients)

for item in ingr_used:
    print(f"The cost of {item['name']} is ${item['ingredient_cost']:.2f} for {item['ingredient_qty']} units.")

我建议使用字典列表来存储配料数据。 然后,该函数使用用户输入获取配方中使用的配料数量,计算这些配料的成本,并返回另一个字典列表,其中包含最终输入的数据(使用的配料数量、价格和名称)

相关问题 更多 >