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)
  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值