SoFunction
Updated on 2024-11-13

A summary of the three ways to write python to determine whether a variable is None or not

There are three main ways to write code that often determines whether a variable is None:

  • The first isif x is None
  • The second one isif not x:
  • The third one isif not x is None(This sentence is clearer.)if not (x is None)) 。

If you think it makes no difference when you write it this way, then you have to be careful, there is a pitfall. Let's take a look at the code first:

>>> x = 1
>>> not x
False
>>> x = [1]
>>> not x
False
>>> x = 0
>>> not x
True
>>> x = [0]     
>>> not x
False

In python None, False, empty string "", 0, empty list [], empty dictionary {}, empty tuple () are equivalent to False , ie:

not None == not False == not '' == not 0 == not [] == not {} == not ()

So when working with lists, if you want to distinguish thex==[]cap (a poem)x==NoneIn both cases, at this pointif not x:There will be problems:

#Python learning exchange group: 531509025

>>> x = []
>>> y = None
>>> 
>>> x is None
False
>>> y is None
True
>>> 
>>> 
>>> not x
True
>>> not y
True
>>> 
>>> 
>>> not x is None
>>> True
>>> not y is None
False
>>>

Maybe you are trying to determine if x is None, but instead you putx==[]The case is also judged in such a way that it will not be possible to distinguish between them.

For pythoners who are used to writing if not x, it is important to be clear that x equals None, False, the empty string "", 0, the empty list [], the empty dictionary {}, the empty tuple () has no effect on your judgment to make it work.

as forif x is not Nonecap (a poem)if not x is Nonewriting style, it is clear that the former is clearer, while the latter runs the risk of the reader misunderstanding theif (not x) is NoneThis is why the former is recommended, and also this is the style recommended by Google

Conclusion:

if x is not NoneIt's the best way to write, clear, no mistakes, and I'll stick with this style of writing from now on.

utilizationif not xThis way of writing presupposes that it must be clear that x equals None, False, the empty string "", 0, the empty list [], the empty dictionary {}, the empty tuple () has no effect on your judgment in order to work.

to this article on python to determine whether the variable is None of the three ways to write a summary of the article is introduced to this, more related to python to determine the content of the variable, please search for my previous articles or continue to browse the following related articles I hope that you will support me more in the future!