Alxyy Kay
Alxyy Kay

Reputation: 11

Can someone help me with the outline of this code?

The problem is I have to write a function that computes the approximate number of calories per hundred grams of a food product, given some information from a nutritional content label and it must have the following arguments:

the code i came up with is:

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)

Can someone suggest how to add a variable that adjustingly calculates the serving per 100g in accordance with the user inputted serving size?

Upvotes: 0

Views: 672

Answers (1)

rhurwitz
rhurwitz

Reputation: 2737

You are close. The exercise requires you to define a function, so the first thing is to separate your code into the function that does the calorie calculations, and the body of your code that will collect user input and display the result.

Regarding the requirement that the result be in terms of a 100 gram portion, you will need to scale the serving size result in terms of the portion size (100 grams).

Example:

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

Upvotes: 1

Related Questions