我正在写一个简短的程序来计算配方中成分的成本。我已经创建了一个包含名称、购买数量、购买价格和用于计算成本的单位的列表。我有一个函数来计算每种成分的单独成本,该成本应传递给主函数,主函数将打印一份声明,显示成分名称和配方中使用的单位数量的成本。 我的问题是,当我打印报表时,它没有获取正确的信息
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。有人能告诉我怎么解决这个问题吗?求你了
我试图解决您的问题,并得出以下代码:
我建议使用字典列表来存储配料数据。 然后,该函数使用用户输入获取配方中使用的配料数量,计算这些配料的成本,并返回另一个字典列表,其中包含最终输入的数据(使用的配料数量、价格和名称)
相关问题 更多 >
编程相关推荐