我不断收到“TypeError: can only concatenate str (not“float”) to str”错误

时间:2021-05-17 21:27:33

标签: python

meal = float(input("Enter the price of the meal:\n"))
if meal>4.00:
    tax = meal * 1.13
    round(tax, 2)
    total = tax + meal
    print("Subtotal: $" + meal + "\n" + "Total Taxes: $" + tax + "\n" + "Total: $" + total)

我正在尝试为学校做作业,当我输出带有附加符号的代码时,它会产生此错误,但如果我使用逗号,它会打印出空格。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

将您的值转换为 str

print("Subtotal: $" + str(meal) + "\n" + "Total Taxes: $" + str(tax) + "\n" + "Total: $" + str(total))

或使用 f 字符串:

print(f"Subtotal: ${meal}\nTotal Taxes: ${tax}\nTotal: ${total}")

答案 1 :(得分:-1)

mealtaxtotal 是浮点数,因此您需要使用 str()

meal = float(input("Enter the price of the meal:\n"))
if meal>4.00:
    tax = meal * 1.13
    round(tax, 2)
    total = tax + meal
    print("Subtotal: $" + str(meal) + "\n" + "Total Taxes: $" + str(tax) + "\n" + "Total: $" + str(total))