无法连接'str'和'float'对象?

时间:2013-06-05 19:31:18

标签: python string concatenation

我们的几何老师给我们一个任务,要求我们创建一个玩具在现实生活中使用几何体的例子,所以我认为制作一个程序来计算填充池需要多少加仑的水是很酷的某种形状,具有一定的尺寸。

到目前为止,这是该计划:

import easygui
easygui.msgbox("This program will help determine how many gallons will be needed to fill up a pool based off of the dimensions given.")
pool=easygui.buttonbox("What is the shape of the pool?",
              choices=['square/rectangle','circle'])
if pool=='circle':
height=easygui.enterbox("How deep is the pool?")
radius=easygui.enterbox("What is the distance between the edge of the pool and the center of the pool (radius)?")
easygui.msgbox=("You need "+(3.14*(float(radius)**2) * float(height)) + "gallons of water to fill this pool.")

我不断收到此错误:

easygui.msgbox=("You need "+(3.14*(float(radius)**2) * float(height))

+ "gallons of water to fill this pool.")
TypeError: cannot concatenate 'str' and 'float' objects

我该怎么办?

3 个答案:

答案 0 :(得分:36)

在连接之前,必须将所有浮点数或非字符串数据类型转换为字符串

这应该可以正常工作:(注意乘法结果的str强制转换)

easygui.msgbox=("You need "+ str(3.14*(float(radius)**2) * float(height)) + "gallons of water to fill this pool.")
直接来自翻译:

>>> radius = 10
>>> height = 10
>>> msg = ("You need "+ str(3.14*(float(radius)**2) * float(height)) + "gallons of water to fill this pool.")
>>> print msg
You need 3140.0gallons of water to fill this pool.

答案 1 :(得分:1)

使用Python3.6 +,您可以使用f-strings设置打印语句的格式。

radius=24.0
height=15.0
print(f"You need {3.14*height*radius**2:8.2f} gallons of water to fill this pool.")

答案 2 :(得分:0)

还有另一种解决方案,您可以使用字符串格式设置(我猜类似于c语言)

这样,您还可以控制精度。

radius = 24
height = 15

msg = "You need %f gallons of water to fill this pool." % (3.14 * (float(radius) ** 2) * float(height))
print(msg)

msg = "You need %8.2f gallons of water to fill this pool." % (3.14 * (float(radius) ** 2) * float(height))
print(msg)

不精确

  

您需要27129.600000加仑的水才能填充该池。

精度为8.2

  

您需要27129.60加仑的水才能填充该池。