无法连接“str”和“float”对象?

2024-09-22 20:22:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我们的几何老师给我们布置了一个作业,要求我们创造一个玩具在现实生活中使用几何的例子,所以我认为制作一个程序来计算一个特定形状和特定尺寸的水池需要多少加仑的水是很酷的。

目前的计划是:

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

我该怎么办?


Tags: ofthetoisfloatfillwhatwill
3条回答

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

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

使用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.")

还有一个解决方案,您可以使用字符串格式(我猜类似于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)

不精确

You need 27129.600000 gallons of water to fill this pool.

精度为8.2

You need 27129.60 gallons of water to fill this pool.

相关问题 更多 >