我正在尝试使用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"就其本身而言,t可以很好地工作,但是当我将其嵌入诸如此类的函数中时:
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)然后我得到一个 NotImplementationError ,说它没有为这种类型实现,有人能解释一下这是怎么工作的吗?
Then I get a NotImplementationError saying it isn't implemented for this type, can anyone explain how this is not working?
推荐答案非数字"或"NaN"是根据IEEE-754标准的一种特殊的浮点值.函数 numpy.isnan()和 math.isnan()测试给定的浮点数是否具有此特殊值(或多个"NaN"值之一).将浮点数以外的任何内容传递给这些函数之一将导致 TypeError .
"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.
要执行您想进行的输入检查,您不应该使用 input().而是使用 raw_input(), try:将返回的字符串转换为 float ,如果失败则处理错误.
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.
示例:
def input_float(prompt): while True: s = raw_input(prompt) try: return float(s) except ValueError: print "Please enter a valid floating point number."@ J.F.塞巴斯蒂安指出,
As @J.F. Sebastian pointed out,
input()执行 eval(raw_input(prompt)),这很可能不是您想要的.
input() does eval(raw_input(prompt)), it's most probably not what you want.
或更明确地说, raw_input 沿字符串传递,一旦发送给 eval ,该字符串将被评估并视为带有输入值的命令而不是输入字符串本身.
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.
更多推荐
使用NumPy的isnan函数检查用户输入
发布评论