
在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
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)