关于None和判断的总结

1 None 是什么?
- 与 C 和 JAVA 不同,Python 中是没有 NULL 的,取而代之的是 None。
- None 是一个特殊的常量,表示变量没有指向任何对象。
- 在 Python 中,None 本身实际上也是对象,有自己的类型 NoneType。
- 你可以将 None 赋值给任何变量,但我们不能创建 NoneType 类型的对象。
obj = None
obj2 = None
print(f"None 的类型:{type(None)}")
print(f"None 的地址:{id(None)}")
print(f"obj 的地址:{id(obj)}")
print(f"obj2 的地址:{id(obj2)}")

[!note] 注意
None 不是 False,None 不是 0,None 不是空字符串。None 和任何其他的数据类型比较永远返回 False。
2 None 和其他类型的比较
-
None 和其他任何类型比较都会返回 False
# None 和其他任何类型比较都会返回 False a = None if a is None and a == None: print("a 是 None") # 会执行 if a == False or a == 0: print("None 不等于 False") # 不会被打印
-
空列表、空字符串、0 之间的比较
-
if 语句判断时,空列表 []、空字典{}、空元组 ()、0 等一系列代表空和无的对象会被转换成 False
a = [] b = () c = {} d = "" e = 0 f = None if (not a) and (not b) and (not c) and (not d) and (not e) and (not f): print("if判断时,空列表[]、空字符串、0、None 等代表空和无的对象会被转换成False")
-
== 和
is判断时,空列表、空字符串不会自动转成Falsea = [] b = () c = {} d = "" e = 0 if a == False or d == False: print("== 时,空列表、空字符串是False!") # 不会执行 else: print("== 时,空列表、空字符串不是False!")
-

浙公网安备 33010602011771号