gpt4 book ai didi

python - 使用 NumPy 的 isnan 函数检查用户输入

转载 作者:太空狗 更新时间:2023-10-30 00:30:25 25 4
gpt4 key购买 nike

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

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 工作正常,但是当我将它嵌入到函数中时,例如在这种情况下:

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 说它没有为这个类型实现,谁能解释这是怎么回事?

最佳答案

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

要进行您想进行的那种输入检查,您不应该使用 input()。相反,使用 raw_input()try: 将返回的字符串转换为 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."

作为@J.F.塞巴斯蒂安指出,

input() does eval(raw_input(prompt)), it's most probably not what you want.

或者更明确地说,raw_input 传递一个字符串,该字符串一旦发送到 eval 将被评估并被视为带有输入值的命令而不是输入字符串本身。

关于python - 使用 NumPy 的 isnan 函数检查用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8507509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com