gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:12:02 24 4
gpt4 key购买 nike

当我运行我的脚本时,我得到一个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. 删除了对 strfloat 的不必要调用。

  3. 合并使用str.format .

关于python - 为什么我会收到 TypeError : unsupported operand type(s) for +,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20551329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com