Difference between if and if is not None

后端 未结 4 982
广开言路
广开言路 2020-12-31 10:14

In writing some XML parsing code, I received the warning:

FutureWarning: The behavior of this method will change in future versions.  Use specific \'len(elem         


        
4条回答
  •  旧巷少年郎
    2020-12-31 10:41

    The behavior of if x is sort of interesting:

    In [1]: def truthy(x):
    ...:     if x:
    ...:         return 'Truthy!'
    ...:     else:
    ...:         return 'Not truthy!'
    ...:     
    
    In [2]: truthy(True)
    Out[2]: 'Truthy!'
    
    In [3]: truthy(False)
    Out[3]: 'Not truthy!'
    
    In [4]: truthy(0)
    Out[4]: 'Not truthy!'
    
    In [5]: truthy(1)
    Out[5]: 'Truthy!'
    
    In [6]: truthy(None)
    Out[6]: 'Not truthy!'
    
    In [7]: truthy([])
    Out[7]: 'Not truthy!'
    
    In [8]: truthy('')
    Out[8]: 'Not truthy!'
    

    So, for example, statements under the conditional if x will not execute if x is 0, None, the empty list, or the empty string. On the other hand if x is not None will only apply when x is exactly None.

提交回复
热议问题