栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python杂记——if obj 和 if obj is None的区别

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python杂记——if obj 和 if obj is None的区别

在python中的条件判断常见的可能有这几种:
if obj;if not obj;if obj isNone; if not obj is None;if obj is not None; if obj == None

那么这几种写法有什么区别呢?

python中None, 空字符串’', 0, 空列表[], 空字典{}, 空元祖, False值都是False, if条件可以用来判断对象是否为空。
而如果一个对象是None的话也就是没有定义,可以使用is None来判断。

测试代码:
测试环境:Ubuntu 18.04 python3.7

def test_is_None():
    l1 = [1, 2, 3, 4]
    l2 = []
    l3 = None

    print("bool(l1): ", bool(l1), "; bool(l2): ", bool(l2), "; bool(l3): ", bool(l3))
    print("bool(not l1): ", bool(not l1), "; bool(not l2): ", bool(not l2), "; bool(not l3): ", bool(not l3))
    print("l1 is None: ", l1  is None, "; l2 is None: ", l2 is None, "; l3 is None: ", l3 is None)
    print("not l1 is None: ", not l1  is None, "; not l2 is None: ", not l2 is None, "; not l3 is None: ", not l3 is None)
    print("l1 is not None: ", l1  is not None, "; l2 is not None: ", l2 is not None, "; l3 is not None: ", l3 is not None)
    print("l1 == None: ", l1  == None, "; l2 == None: ", l2 == None, "; l3 == None: ", l3 == None)
test_is_None

测试结果:

bool(l1):  True ; bool(l2):  False ; bool(l3):  False
bool(not l1):  False ; bool(not l2):  True ; bool(not l3):  True
l1 is None:  False ; l2 is None:  False ; l3 is None:  True
not l1 is None:  True ; not l2 is None:  True ; not l3 is None:  False
l1 is not None:  True ; l2 is not None:  True ; l3 is not None:  False
l1 == None:  False ; l2 == None:  False ; l3 == None:  True
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/857617.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号