Skip to main content
 首页 » 编程设计

python之在 python 中,当参数数据类型为 NaN 时,如何返回 NaN 而不是 TypeError

2025年05月04日17leader

例如我定义了一个需要多个输入参数的函数,如果一些关键字参数没有赋值,通常会有一个TypeError消息,但我想改变它,输出一个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) 只接受一个数字作为输入,如果输入了一些其他数据类型,如 string = 'whatever',我不想只输出默认错误消息,我想要它输出类似于 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') 

The Python Tutorial有一个关于这个主题的精彩章节。