繁体   English   中英

有人可以帮我概述一下这段代码吗?

[英]Can someone help me with the outline of this code?

问题是我必须编写一个 function 来计算每百克食品的大致卡路里数,给出来自营养成分 label 的一些信息,它必须具有以下 ZDBC11CAA5BDA99F77E6FB4DABD882EED7

  • 份量(克)
  • 一份中的脂肪克数
  • 一份中碳水化合物的克数
  • 一份蛋白质的克数

我想出的代码是:

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 克的份量吗?

你很亲密。 该练习要求您定义一个 function,因此首先要将您的代码分成进行卡路里计算的 function,以及将收集用户输入并显示结果的代码主体。

关于以 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))

Output:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM