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

标签 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

我该怎么办?

最佳答案

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

这应该可以正常工作:(注意乘法结果的 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.

关于python - 无法连接 'str' 和 'float' 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16948256/

相关文章:

java - java中的字符串对象和引用

python - 在 Theano 中结合标量和向量来计算 Hessian

python - 遍历二维 python 列表

python - sleep 而不中断程序

javascript - 在 JavaScript 中搜索最后一个词

JavaScript 将字符串转换为逗号列表

python - 在scikit-learn中拟合后如何得到方程?

Python正则表达式匹配行中的第二个或第三个单词

mysql - 选择/插入时出现奇数 CONCAT 错误

php - 我应该使用 GROUP_CONCAT 吗?