I'm trying to use NumPy to check if user input is numerical. I've tried using:
import numpy as np
a = input("\n\nInsert A: ")
if np.isnan(a):
print 'Not a number...'
else:
print "Yep,that's a number"
On its own t works fine, however when I embed it into a function such as in this case:
import numpy as np
def test_this(a):
if np.isnan(a):
print '\n\nThis is not an accepted type of input for A\n\n'
raise ValueError
else:
print "Yep,that's a number"
a = input("\n\nInsert A: ")
test_this(a)
Then I get a NotImplementationError
saying it isn't implemented for this type, can anyone explain how this is not working?
"Not a Number" or "NaN" is a special kind of floating point value according to the IEEE-754 standard. The functions numpy.isnan()
and math.isnan()
test if a given floating point number has this special value (or one of several "NaN" values). Passing anything else than a floating point number to one of these function results in a TypeError
.
To do the kind of input checking you would like to do, you shouldn't use input()
. Instead, use raw_input()
,try:
to convert the returned string to a float
, and handle the error if this fails.
Example:
def input_float(prompt):
while True:
s = raw_input(prompt)
try:
return float(s)
except ValueError:
print "Please enter a valid floating point number."
As @J.F. Sebastian pointed out,
input()
doeseval(raw_input(prompt))
, it's most probably not what you want.
Or to be more explicit, raw_input
passes along a string, which once sent to eval
will be evaluated and treated as though it were command with the value of the input rather than the input string itself.