poptrt00 poptrt00 - 7 days ago 5
Python Question

Grok Learning: Halve this TypeError

Newbie at programming, doing Grok to learn more. So I have to write a program that reads in a whole number and prints out that number divided by two. This is my code:

a= int(input("Number: "))
h= a/2
print("Half number: " + h)


But I keep getting this

Number: 6
Traceback (most recent call last):
File "program.py", line 3, in <module>
print("Half number: " + h)
TypeError: Can't convert 'float' object to str implicitly


I don't see anything wrong with my code and I have no idea what the error is. Any idea what's wrong??

Answer

The expression:

"Half number: " + h

is trying to add a string to a float. You can add strings to strings:

"This string" + ", then this string"

and floats to floats:

100.0 + 16.8

but Python isn't willing to let you add strings and floats. (In the error message above, Python has processed the first string and the addition, and it now expects a string -- that's why you get the error that it can't -- or at least won't -- convert a 'float' number to a string.)

You can tell Python this is what you really want it to do in a few ways. One is to use the built-in str() function which converts any object to some reasonable string representation, ready to be added to another string:

 h = 100
 "You can add a string to this: " + str(h)
Comments