类型错误:只能将 str(不是“float")连接到 str [英] TypeError: can only concatenate str (not "float") to str

查看:62
本文介绍了类型错误:只能将 str(不是“float")连接到 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")

错误信息:

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

推荐答案

关于如何解决这个问题,您有一些选择

You have some options about how to go about this

使用 peso = str(peso)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")

或者您可以在执行 print 时将它们转换为 str,这样您就可以根据需要将值保留为 floats做更多的计算,而不必一遍又一遍地来回转换

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

这篇关于类型错误:只能将 str(不是“float")连接到 str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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