Reputation: 1
When I try this:
import math
g = input("Put your number here: ")
print ("The square root of you number is: " + int(math.sqrt(g)))
And I write 7
as my input per se, I get this error message:
TypeError: a float is required
I would greatly appreciate any solutions and or pointers. Thanks!
Upvotes: 0
Views: 1174
Reputation:
You are getting a TypeError
because math.sqrt
requires a number (either a float or an integer):
>>> import math
>>> math.sqrt(4.0)
2.0
>>> # Integers work too, even though the error message doesn't mention them
>>> math.sqrt(4)
2.0
>>> math.sqrt('4')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a float is required
>>>
However, input
returns a string object in Python 3.x:
>>> x = input()
7
>>> type(x)
<class 'str'>
>>>
This means that g
will be a string when you give it to math.sqrt
.
To fix the problem, you need to do two things:
Make g
a number before giving it to math.sqrt
. This can be done with either int
or float
.
Convert the result back into a string to add it to the output string:
Below is a demonstration:
>>> import math
>>> g = int(input("Put your number here: "))
Put your number here: 7
>>> print ("The square root of you number is: " + str(int(math.sqrt(g))))
The square root of you number is: 2
>>>
Note however that the last line can be rewritten a little more cleanly like so:
print ("The square root of you number is: %d" % math.sqrt(g))
Upvotes: 1
Reputation: 7209
g = float(input("Put your number here: "))
With input() you get string, but float (or int) is needed.
Upvotes: 2