我的程序运行,但是输入答案后,我仍然收到错误消息
“ TypeError:一元+的错误操作数类型:'str'
def calculateCaloriesFromFat(fatGrams):
caloriesFromFat = fatGrams * 9
return caloriesFromFat
def calculateCaloriesFromCarbs(carbGrams):
caloriesFromCarbs = carbGrams * 4
return caloriesFromCarbs
def main():
userFatGrams = float(input("How many Fat Grams?"))
userCarbGrams = float(input("How many Carb Grams?"))
caloriesFromFat = calculateCaloriesFromFat(userFatGrams)
caloriesFromCarbs = calculateCaloriesFromCarbs(userCarbGrams)
print("calories from fat", + format(caloriesFromFat, "f"),
"calories from carbs", + format(caloriesFromCarbs, "f"))
main()
答案 0 :(得分:1)
您在这里不需要+
标记:
print("calories from fat", format(caloriesFromFat, "f"),
"calories from carbs", format(caloriesFromCarbs, "f"))
答案 1 :(得分:0)
以下方法应该起作用:
def calculateCaloriesFromFat(fatGrams):
caloriesFromFat = fatGrams * 9
return caloriesFromFat
def calculateCaloriesFromCarbs(carbGrams):
caloriesFromCarbs = carbGrams * 4
return caloriesFromCarbs
def main():
userFatGrams = float(input("How many Fat Grams?"))
userCarbGrams = float(input("How many Carb Grams?"))
caloriesFromFat = calculateCaloriesFromFat(userFatGrams)
caloriesFromCarbs = calculateCaloriesFromCarbs(userCarbGrams)
print("calories from fat " + format(caloriesFromFat, "f") + "calories from carbs " + format(caloriesFromCarbs, "f"))
main()
但是,请考虑将format(caloriesFromFat, "f")
更改为:
print("calories from fat " + str(caloriesFromFat) + " calories from carbs " + str(caloriesFromCarbs))
这样做,您将消除不需要的任何额外零。