Grok Learning: Halve this TypeError

Question:

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?

Asked By: poptrt00

||

Answers:

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)
Answered By: K. A. Buhr

a= int(input(“Number: “))

h= a/2

print(‘Half number:’, h)
Without the spaces in between though

Answered By: heidiHo11

Here is a very simple way to do it.

Here’s a sample solution from Grok Learning:

n = int(input('Number: '))
print('Half number:', n/2)

Here’s my explanation below:

As you might’ve already guessed, n here is a variable. And in this code, we will be assigning some information to n. int(input('Number ')) is the statement that Python will then read, and follow. int() tells Python that the input will be an integer, and input() allows the user to input whatever they would like to input. n/2 is simply another way of saying “n divided by two”. print() tells Python to print a statement, and so print('Half number:', n/2) will print out that “Half number” is simply just half of the number entered above.

Here’s an example of what the output should look like:

Number: 6
Half number: 3

(In that example, the input was 6.)

So, yes, I know that you may already know this stuff but I am leaving this information for people who may visit this website in the future. The error that you had was that you used a +, when you should’ve used a ,. Python is pretty strict when it comes to processing what you’re saying, so it didn’t allow you to put a str and an int together using a +. So next time, remember to use a ,.

I hope this helps you.

Answered By: CodeAJ
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.