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

前端 未结 3 2087
鱼传尺愫
鱼传尺愫 2020-11-28 16:03

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.

相关标签:
3条回答
  • 2020-11-28 16:31

    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")
    
    0 讨论(0)
  • 2020-11-28 16:37

    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)
    
    0 讨论(0)
  • 2020-11-28 16:45

    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
    
    0 讨论(0)
提交回复
热议问题