python 判断常量和None的等值/不等 是用==/!= 还是 is/is not

is 是检查两个对象是否指向同一块内存空间,而 == 是检查他们的值是否相等 

在一些判断是否相等/不相同的情况下,他们的使用有区别的

以下是 flake8给出的检测提示:

 use ==/!= to compare constant literals (str, bytes, int, float, tuple)

 comparison to None should be 'if cond is None:'

如下例子代码:

a=8
if(a is not 9):
    print("a not 9")

会有报错提示:

SyntaxWarning: "is not" with a literal. Did you mean "!="?
  if(a is not 9):
a not 9

程序能够出结果,但是会有警示。if里is not换成!= 报警消失

 对于字符型,数字型、tuple型字面量常量形式的比较,要使用==/!=

对于None的比较,建议使用is/is not

a='ss'

if(a is None):
    print("a is None")
if(a is not None):
    print("a is not None")

 a is not None

另外对于list 与常量相比值是否相等也是 ==/!=,is/is not 会另外查找id是否也相等

b=[1,2]
if(b==[1,2]):
    print("== 1,2元素")

if(b is [1,2]):
    print("is 1,2元素")

打印:

== 1,2元素

注意!

在Flask alchecmy 框架中,filter中不能使用is none来判断空。使用==/!=来与空做判断

 

in null:

 query.filter(User.name==None)

is not null:

query.fillter(User.name!=None)

你可能感兴趣的:(python,开发语言)