Checking user input using isnan function of NumPy
Asked Answered
A

3

5

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?

Antecedent answered 14/12, 2011 at 15:57 Comment(1)
1. avoid from numpy import *, you could import numpy as np and later use np.isnan(), etc instead. 2. Don't compare with True directly use if np.isnan(a) instead. 3. input() does eval(raw_input(prompt)) it's most probably not what you want.Tamatamable
G
11

"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() does eval(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.

Gasholder answered 14/12, 2011 at 16:13 Comment(0)
V
2

One of the most encompassing ways of checking if a user input is a valid number in Python is trying to convert it to a float value, and catch the exception.

As denoted in the comments and other answers, the check for NaN has nothing to do with valid user numeric input - rather, it checks if a numeric object has the special value of Not a Number.

def check_if_numeric(a):
   try:
       float(a)
   except ValueError:
       return False
   return True
Vanillic answered 14/12, 2011 at 16:17 Comment(0)
T
0
a = raw_input("\n\nInsert A: ")

try: f = float(a)
except ValueError:
     print "%r is not a number" % (a,)
else:
     print "%r is a number" % (a,)
Tamatamable answered 14/12, 2011 at 16:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.