为什么我得到TypeError:不支持的操作数类型+

2024-06-26 02:33:58 发布

您现在位置:Python中文网/ 问答频道 /正文

当我运行脚本时,我得到一个TypeError。 这是我所有的代码:

lawnCost = ("£15.50")
lengthLawn = float(input("Lengh of lawn: "))
widthLawn = float(input("Width of lawn: "))

totalArea = (lengthLawn) * (widthLawn)

print (("The total area of the lawn is ")+str(totalArea)+str("m²"))

totalCost = (totalArea) * float(15.50)

print ("The cost of lawn per m² is £15.50")
print ("The total cost for the lawn is ")+str(totalCost)

这是我得到的错误:

^{pr2}$

如果有人能帮我指出正确的方向那就太好了,谢谢。在

如果有帮助的话,我可以在Windows7x64上运行Python3.3。在


Tags: oftheinputisfloattotalprintcost
1条回答
网友
1楼 · 发布于 2024-06-26 02:33:58

在最后一行,str(totalCost)必须在print的圆括号内

print ("The total cost for the lawn is "+str(totalCost))

这是因为在python3.x中,print返回{}。因此,您的代码实际上是在尝试这样做:

^{pr2}$

另外,如果需要,下面是脚本的一个版本,它更干净、更高效:

lawnCost = "£15.50"
lengthLawn = float(input("Lengh of lawn: "))
widthLawn = float(input("Width of lawn: "))

totalArea = lengthLawn * widthLawn

print("The total area of the lawn is {}m²".format(totalArea))

totalCost = totalArea * 15.50

print("The cost of lawn per m² is £15.50")
print("The total cost for the lawn is {}".format(totalCost))

基本上,我做了三件事:

  1. 删除了不必要的括号和print后的多余空格。

  2. 删除了对strfloat的不必要调用。

  3. 合并使用^{}

相关问题 更多 >