Python 无法连接';str';和';浮动';物体?
我们的几何老师给我们布置了一个作业,要求我们创建一个玩具在现实生活中使用几何的例子,所以我认为制作一个程序来计算填充一个特定形状和尺寸的水池需要多少加仑的水是很酷的 以下是迄今为止的计划:Python 无法连接';str';和';浮动';物体?,python,string,concatenation,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
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
我该怎么办?所有浮点或非字符串数据类型必须在连接之前强制转换为字符串 这应该可以正常工作:(注意乘法结果的
str
cast)
直接从口译员那里:
>>> 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.
还有一个解决方案,您可以使用字符串格式(我想类似于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加仑的水来填满这个水池
使用Python3.6+,可以使用格式化打印语句
radius=24.0
height=15.0
print(f"You need {3.14*height*radius**2:8.2f} gallons of water to fill this pool.")
这是唯一的解决办法,真的吗?您必须将其放入
str()
函数中吗?有点郁闷
radius=24.0
height=15.0
print(f"You need {3.14*height*radius**2:8.2f} gallons of water to fill this pool.")