Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking user input using isnan function of NumPy

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?

like image 272
George Burrows Avatar asked Dec 14 '11 15:12

George Burrows


1 Answers

"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.

like image 142
Sven Marnach Avatar answered Sep 30 '22 07:09

Sven Marnach