2011-12-14 36 views
5

我試圖使用numpy的檢查,如果用戶輸入數值,我用已經試過:NumPy的 - 使用isnan(x)的

from numpy import * 

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

if isnan(a) == True: 
    print 'Not a number...' 
else: 
    print "Yep,that's a number" 

它自己和然而,當它工作得很好,我它嵌入到一個函數,例如在這種情況下:從numpy的進口

*

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) 

然後我得到一個NotImplementationError說這是不是這種類型的實現,誰能解釋這是不工作?

任何幫助將不勝感激,再次感謝。

+2

是您的目標是測試是否值輸入的用戶是一個有效的數字? – 2011-12-14 16:00:14

回答

11

根據IEEE-754標準,「非數字」或「NaN」是一種特殊的浮點值。函數numpy.isnan()math.isnan()測試給定浮點數是否具有此特殊值(或多個「NaN」值之一)。將除浮點數以外的任何其他數據傳遞給這些函數之一將導致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()確實eval(raw_input(prompt)),這很可能不是你想要的。

或者更明確的,沿raw_input一個字符串,其一次發送給eval通行證將被評估和治療,就好像是與輸入的值,而不是輸入字符串本身命令。

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

在Python中檢查用戶輸入是否爲有效數字的最普遍方法之一是嘗試將其轉換爲浮點值並捕獲異常。

如註釋和其他答案中所述,NaN檢查與有效的用戶數字輸入無關 - 而是檢查數值對象是否具有特殊值Not Not Number。

def check_if_numeric(a): 
    try: 
     float(a) 
    except ValueError: 
     return False 
    return True 
0

您可以檢查直接輸入類型:

a = input("\n\nInsert A: ") 
num_types = ("int", "float", "long", "complex") 

if type(a).__name__ in num_types 
    print "Yep,that's a number"  
else: 
    print '\n\nThis is not an accepted type of input for A\n\n' 
    raise ValueError