Python调和平均计算代码抛出TypeError:只能将字符串与字符串拼接,无法拼接浮点数
Let’s work through this error and get your code running smoothly.
First, let’s break down why you’re seeing that TypeError: can only concatenate str (not "float") to str message:
When building your mensagem string, you’re trying to directly add float values (x, y, and your calculated harmonic average) to strings. Python doesn’t allow mixing string and non-string types in concatenation — it needs everything to be a string first.
Here are three straightforward ways to fix this:
1. Explicitly convert floats to strings with str()
Wrap each float variable in str() to turn it into a string before concatenation:
mensagem = "A média harmonica de "+str(x)+" e "+str(y)+" é: "+str(média_harmonica)
2. Use f-strings (cleanest and most readable option, Python 3.6+)
F-strings let you embed variables directly in strings, and Python automatically handles type conversion for you. You can even add formatting to control decimal places for cleaner output:
# Basic version mensagem = f"A média harmonica de {x} e {y} é: {média_harmonica}" # With 2 decimal places for neater results mensagem = f"A média harmonica de {x:.2f} e {y:.2f} é: {média_harmonica:.2f}"
3. Use str.format()
This is a slightly older formatting method that still works reliably:
# Basic version mensagem = "A média harmonica de {} e {} é: {}".format(x, y, média_harmonica) # With decimal formatting mensagem = "A média harmonica de {:.2f} e {:.2f} é: {:.2f}".format(x, y, média_harmonica)
Bonus: Avoid overwriting your function
One quick note — you’re assigning your calculated result to média_harmonica, which is the same name as your function. This overwrites the function, so if you tried to call média_harmonica() later in your code, it would fail. It’s better to use a distinct variable name like resultado.
Here’s the full revised code using f-strings and the improved variable name:
def média_harmonica(x,y): return 2/((1/x)+(1/y)) x = float(input("请输入x的数值:")) y = float(input("请输入y的数值:")) resultado = média_harmonica(x, y) mensagem = f"A média harmonica de {x} e {y} é: {resultado}" print(mensagem)
内容的提问来源于stack exchange,提问作者random girl

