Python 3使用IF或TRY测试无。意外的结果

时间:2019-03-08 01:07:34

标签: python try-catch except

我说出意外,因为我显然没有正确地考虑“尝试并无”。 我到达这里是因为我正在调用一个函数以返回MyVar的值,然后尝试进行尝试以确保该函数未返回None。 像这样:

def Myfunct():
    return "Some_URL"
MyVar = Myfunct()
try:
    MyVar is not None:
    pass

我无法获得预期的TRY结果。因此,我明确声明了值并再次进行了测试。 通过IF测试None可以得到正确的结果,但是使用TRY进行相同的操作则会得到意外的结果,这来自以下代码:

Type of My_Var is: <class 'str'> with value:  Some_URL
IF is None: False
IF is not None: True
TRY is None: True
TRY is not None: True

Try和None都返回True。那怎么可能?关于检查是否已设置值,我缺少什么

My_Var = None
My_Var = "Some_URL"
print ("Type of My_Var is:", type(My_Var), "with value: ", My_Var)

if My_Var is None:
    print ("IF is None: True")
else:
    print ("IF is None: False")

if My_Var is not None:
    print ("IF is not None: True")
else:
    print ("IF is not None: False")    

try:
    My_Var is None
    print ("TRY is None: True" )
    pass

except Exception as e:
    print ("TRY is None: False" )

try:
    My_Var is not None
    print ("TRY is not None: True" )
    pass

except Exception as e:
    print ("TRY is not None: False" )

1 个答案:

答案 0 :(得分:0)

try不在乎值是TrueFalseNone还是其他任何值。如果没有错误发生,try将执行一段代码,如果确实发生错误,则会执行except

See more here