`TypeError:一元+的错误操作数类型:'str'

时间:2020-09-29 18:39:29

标签: python typeerror

我的程序运行,但是输入答案后,我仍然收到错误消息

“ 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()

2 个答案:

答案 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))

这样做,您将消除不需要的任何额外零。