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?

Georgy
  • 12,464
  • 7
  • 65
  • 73
George Burrows
  • 3,391
  • 9
  • 31
  • 31
  • 3
    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. – jfs Dec 14 '11 at 16:20

3 Answers3

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.

mpacer
  • 3,009
  • 2
  • 16
  • 15
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
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
jsbueno
  • 99,910
  • 10
  • 151
  • 209
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,)
jfs
  • 399,953
  • 195
  • 994
  • 1,670