NumPy - 使用isnan(x)

Geo*_*ows 5 python numpy notimplementedexception

我正在尝试使用numpy检查用户输入是否为数字,我尝试过使用:

from numpy import *

a = input("\n\nInsert A: ")

if isnan(a) == True:
    print 'Not a number...'
else:
    print "Yep,that's a number"
Run Code Online (Sandbox Code Playgroud)

它本身就可以正常工作,但是当我将它嵌入到一个函数中时,例如:

来自numpy import*

def test_this(a):

    if isnan(a) == True:
        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)
Run Code Online (Sandbox Code Playgroud)

然后我得到一个NotImplementationError,说它没有为这种类型实现,任何人都可以解释这是如何工作的?

任何帮助将不胜感激,再次感谢.

Sve*_*ach 11

"非数字"或"NaN"是根据IEEE-754标准的特殊浮点值.函数numpy.isnan()math.isnan()测试给定的浮点数是否具有此特殊值(或几个"NaN"值之一).将除浮点数之外的任何内容传递给其中一个函数会导致a TypeError.

要做你想做的那种输入检查,你不应该使用input().相反,使用raw_input(),try:将返回的字符串转换为a float,并在失败时处理错误.

例:

def input_float(prompt):
    while True:
        s = raw_input(prompt)
        try:
            return float(s)
        except ValueError:
            print "Please enter a valid floating point number."
Run Code Online (Sandbox Code Playgroud)

正如@JF塞巴斯蒂安指出的那样,

input()是的eval(raw_input(prompt)),它很可能不是你想要的.

或者更明确地说,raw_input传递一个字符串,一旦发送到该字符串eval将被评估和处理,就好像它是带有输入值而不是输入字符串本身的命令.