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

编程入门 行业动态 更新时间:2024-10-19 22:37:57
本文介绍了使用NumPy的isnan函数检查用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用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函数检查用户输入

本文发布于:2023-10-26 18:48:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531036.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   用户   NumPy   isnan

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!