0、not
是什么
在python中not
是逻辑判断词,用于布尔型True和False之前
a = not Ture
# a == False
b = not False
# b == True
1、not
的用法
(1)判断语句
if not a:
# 如果a是False,执行的语句
(2)判断元素是否在列表或者字典中
a = 5
b = [1,2,3,4]
if a not in b:
b.append(a)
2、刷题是判断变量不为None
if not x:
if x is not None
💡首先明确一点
在Python中,None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()都相当于False
if not x:
# list1是空列表
list1 = []
# list2不存在
list2 = None
# 使用 `if not x:`判断
if not list1:
print("list1可以执行") # not [] -> True
if not list2:
print("list2可以执行") # not None ->True
>>>list1可以执行
>>>list2可以执行
❌不可以区分空列表和None
如果要使用if not x:
,必须清楚x等于None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响
if x is not None
# list1是空列表
list1 = []
# list2不存在
list2 = None
# 使用 `if x is not None`判断
if list1 is not None:
print("list1可以执行")
if list2 is not None:
print("list2可以执行")
>>>list1可以执行 `if 空集 is not None` -> True
# `if None is not None` ->False
⭐️可以区分空列表和None
if x is not None
是最好的写法,清晰,不会出现错误,以后坚持使用这种写法。