比较两个非类型的变量时处理TypeError的问题-Python 3.6



我正在尝试处理一个TypeError异常,其中两个变量都等于None

我想使它们中的每一个都等于一个浮点0。如果其中一个变量是float,一个是NoneType,它似乎可以正确地将NoneType变量转换为0,并返回float,正如我所期望的那样,但当两者都是NoneType:时,我仍然会得到类型错误

'<' not supported between instances of 'float' and 'NoneType'

为什么会发生这种情况?我希望以下函数返回0。这是我的代码:

def test():
market_price = None
low_price = None
try:
if market_price < low_price:
market_price = low_price
except TypeError:
if market_price is None:
market_price = 0.
elif low_price is None:
low_price = 0.
if market_price < low_price:
market_price = low_price
return market_price
print(test())

在此代码块中,将market_price设置为0或将low_price设置为0。两者均为None,因此只有market_price设置为0,low_price保持None,比较失败。

if market_price is None:
market_price = 0.
elif low_price is None:
low_price = 0.

将以下语句拆分为:

if market_price is None:
market_price = 0
if low_price is None:
low_price = 0

这样,程序将正确地将两个变量设置为0。

所以,让我们来复习一下您的代码。。。(带#的评论(

def test():
market_price = None  #  Sets variables to None
low_price = None
try:
if market_price < low_price:  # This will ALWAYS throw error because < isn't a good operator for comparing None
market_price = low_price  # Never gets here
except TypeError:                 # This function will Always hit exception (which is probably already wrong)
if market_price is None:  # This is true
market_price = 0.     # so this gets set to a float
elif low_price is None:   # Since above is true this doesn't get checked (ie elif rather than a regular if)
low_price = 0.        # This never gets set
if market_price < low_price:  # You are comparing None with less than operators again (which would fail)
market_price = low_price
return market_price
print(test())

相关内容

最新更新