无法连接“ str”和“ float”对象? [英] Cannot concatenate 'str' and 'float' objects?

查看:68
本文介绍了无法连接“ str”和“ float”对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的几何老师给了我们一个作业,要求我们创建一个玩具在现实生活中何时使用几何的示例,所以我认为编写一个程序来计算填充水池需要多少加仑水会很酷。

Our geometry teacher gave us an assignment asking us to create an example of when toy use geometry in real life, so I thought it would be cool to make a program that calculates how many gallons of water will be needed to fill a pool of a certain shape, and with certain dimensions.

这是到目前为止的程序:

Here is the program so far:

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

我该怎么办?

推荐答案

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

All floats or non string data types must be casted to strings before concatenation

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

This should work correctly: (notice the str cast for multiplication result)

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.

这篇关于无法连接“ str”和“ float”对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆