Checking user input using isnan function of NumPy

安稳与你 提交于 2021-02-07 14:20:21

问题


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?


回答1:


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




回答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



回答3:


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,)


来源:https://stackoverflow.com/questions/8507509/checking-user-input-using-isnan-function-of-numpy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!