TypeError: can only concatenate str (not “float”) to str

I’m trying to make a program that compares the density of a certain mass and volume to a list of densities of compounds, and return the type of compound I am analyzing.

This is the part of the code that is returning an error:

peso = float(input("Qual o peso do plastico da sua protese?"))
volume = float(input("Qual o volume do material?"))
str(peso)
str(volume)

def resultados():
  print('O peso do plastico é de ' + peso, end="", flush=True)

resultados()
  print(' g e tem um volume de ' + volume + "dm^3")

The error message:

TypeError                                 Traceback (most recent call last)
<ipython-input-9-d36344c01741> in <module>()
      8     print('O peso do plastico é de ' + peso, end="", flush=True)
      9 
---> 10 resultados()
     11 print(' g e tem um volume de ' + volume + "dm^3")
     12 #############

<ipython-input-9-d36344c01741> in resultados()
      6 
      7 def resultados():
----> 8     print('O peso do plastico é de ' + peso, end="", flush=True)
      9 
     10 resultados()

TypeError: can only concatenate str (not "float") to str

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You have some options about how to go about this

Using peso = str(peso) and same for volume = str(volume)

peso = float(input("Qual o peso do plastico da sua protese?"))
volume = float(input("Qual o volume do material?"))
peso = str(peso)
volume = str(volume)

def resultados():
  print('O peso do plastico é de ' + peso, end="", flush=True)

resultados()
print(' g e tem um volume de ' + volume + "dm^3")

Or you could just convert them to str when you are performing your print this way you can preserve the values as floats if you want to do more calculations and not have to convert them back and forth over and over

peso = float(input("Qual o peso do plastico da sua protese?"))
volume = float(input("Qual o volume do material?"))

def resultados():
  print('O peso do plastico é de ' + str(peso), end="", flush=True)

resultados()
print(' g e tem um volume de ' + str(volume) + "dm^3")

Method 2

You have to assign the cast to the variable. Onlystr(peso) doesn’t modify it. Because str() returns a str type. So, you need to do that:

peso = str(peso)

Method 3

Use formatted string

str_val = "Hello"
int_val = 1234
msg = f'String and integer concatenation : {str_val} {int_val}'

Output

String and integer concatenation : Hello 1234


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x