Cannot concatenate 'str' and 'float' objects?

110,176

Solution 1

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

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

straight from the interpreter:

>>> 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.

Solution 2

There is one more solution, You can use string formatting (similar to c language I guess)

This way you can control the precision as well.

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)

without precision

You need 27129.600000 gallons of water to fill this pool.

With precision 8.2

You need 27129.60 gallons of water to fill this pool.

Solution 3

With Python3.6+, you can use f-strings to format print statements.

radius=24.0
height=15.0
print(f"You need {3.14*height*radius**2:8.2f} gallons of water to fill this pool.")
Share:
110,176
user2443381
Author by

user2443381

Updated on October 03, 2020

Comments

  • user2443381
    user2443381 over 3 years

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

    i keep getting this error though:

    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
    

    what do i do?

  • Toskan
    Toskan over 5 years
    this is the only solution, really? you have to put it into a str() function? a bit depressing