簡體   English   中英

python中,當參數數據類型為NaN時,如何返回NaN,而不是TypeError

[英]In python, when argument data type are NaN, how to return an NaN, not an TypeError

例如,我定義了一個function,它需要多個輸入arguments,如果某些關鍵字arguments沒有被分配,通常會有一個TypeError消息,但我想將其更改為output結果為NaN,可以嗎?

def myfunc( S0, K ,r....):
    if  S0 = NaN or .....:

怎么做? 非常感激。

編輯:

def myfunc(a):
    return a / 2.5 + 5

print myfunc('whatever')

>python -u "bisectnewton.py"
Traceback (most recent call last):
  File "bisectnewton.py", line 6, in <module>
    print myfunc('whatever')
  File "bisectnewton.py", line 4, in myfunc
    return a / 2.5 + 5
TypeError: unsupported operand type(s) for /: 'str' and 'float'
>Exit code: 1

我想要的是,myfunc(a) 只接受一個數字作為輸入,如果輸入了一些其他數據類型,如字符串 = 'whatever',我不想只是 output 一個默認錯誤消息,我想要它 output類似 return 'NaN' 的東西告訴其他人輸入應該是一個數字。

現在我把它改成了這個,但還是不行,順便說一句,和 NaN 不一樣嗎? 我認為他們是不同的。

def myfunc(S0):
    if math.isnan(S0):
        return 'NaN'
    return a / 2.5 + 5

print myfunc('whatever')

>python -u "bisectnewton.py"
Traceback (most recent call last):
  File "bisectnewton.py", line 8, in <module>
    print myfunc('whatever')
  File "bisectnewton.py", line 4, in myfunc
    if math.isnan(S0):
TypeError: a float is required
>Exit code: 1

謝謝!

您可以捕獲TypeError並對其進行任何處理:

def myfunc(a):
  try:
    return a / 2.5 + 5
  except TypeError:
    return float('nan')

print myfunc('whatever')

Python教程在這一主題上有一章非常出色。

def myfunc(S0 = None, K = None, r = None, ....):
    if S0 is None or K is None or r is None:
        return NaN

是的,要生成NaN,您可以進行float('nan')

>>> import math
>> float('nan')
nan
>>> math.isnan(float('nan'))
True

所以,你可以return float('nan')無論你想返回nan 我建議您只提出例外。

如果你不想使用 TypeError,那么使用 AttributeError 怎么樣?

def myfunc(a):
  try:
    return a / 2.5 + 5
  except AttributeError:
    return float('nan')

print myfunc('whatever')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM