Skip to main content
 首页 » 编程设计

python之为什么我会收到 TypeError : unsupported operand type(s) for +

2025年05月04日22pander-it

当我运行我的脚本时,我得到一个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) 

这是我得到的错误:

TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' 

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

此外,如果有帮助,我正在 Windows 7 x64 上运行 Python 3.3。

请您参考如下方法:

在最后一行中,str(totalCost) 需要在 inside print 的括号内:

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

这是因为 print 在 Python 3.x 中返回 None。所以,您的代码实际上是在尝试这样做:

None+str(totalCost) 

此外,如果您需要,下面是您的脚本版本,它更简洁、更高效:

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. 删除了对 str 和 float 的不必要调用。

  3. 合并使用str.format .