有人可以帮助我了解此代码的大纲吗?

时间:2021-04-17 18:43:55

标签: python

问题是我必须编写一个函数来计算每 100 克食品的近似卡路里数,给出来自营养成分标签的一些信息,并且它必须具有以下参数:

  • 份量(以克为单位)
  • 一份脂肪的克数
  • 一份碳水化合物的克数
  • 一份蛋白质的克数

我想出的代码是:

name=str(input("enter the name of the item: "))
serving = int(input("Enter the serving size in gram: "))
fat = float(input("Enter the grams of fat in a serving: "))
carb = float(input("Enter the grams of carbohydrates in a serving: "))
protein = float(input("Enter the grams of protein in a serving: "))
proteinValue = int(protein) * 4
carbValue = int(carb) * 4
fatValue = int(fat) * 9
servingValue = int(serving) / int(fatValue) + int(carbValue) + int(proteinValue) * 100
print(name)
print(servingValue)

有人可以建议如何添加一个变量,根据用户输入的份量来调整计算每 100 克的份量吗?

1 个答案:

答案 0 :(得分:1)

你很近。该练习要求您定义一个函数,因此首先要将您的代码分为进行卡路里计算的函数和用于收集用户输入并显示结果的代码主体。

关于结果以 100 克份为单位的要求,您需要根据份量(100 克)来调整份量结果。

示例:

def calculate_portion_calories(serving_grams, fat_grams, carb_grams, protein_grams, portion_grams=100):
    calories_per_serving = protein_grams * 4 + carb_grams * 4 + fat_grams * 9
    portion_serving_ratio = portion_grams / serving_grams
    
    return portion_serving_ratio * calories_per_serving

food_name = input("Name of food: ")
serving_grams = int(input("Serving size in gram: "))
fat_grams = float(input("Grams of fat in a serving: "))
carb_grams = float(input("Gams of carbohydrates in a serving: "))
protein_grams = float(input("Enter the grams of protein in a serving: "))


print(food_name)
print(calculate_portion_calories(serving_grams, fat_grams, carb_grams, protein_grams))

输出:

Name of food:  Candy Bar
Serving size in gram:  50
Grams of fat in a serving:  20
Gams of carbohydrates in a serving:  20
Enter the grams of protein in a serving:  10
Candy Bar
600.0