Python语法总结:not(常出现错误)

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是最好的写法,清晰,不会出现错误,以后坚持使用这种写法。

相关推荐

  1. Python语法总结not出现错误

    2024-04-04 06:50:03       37 阅读
  2. Linux编码出现错误

    2024-04-04 06:50:03       38 阅读
  3. python用知识总结

    2024-04-04 06:50:03       33 阅读
  4. Nginx出现403 Forbidden、404 Not Found错误的解决方案

    2024-04-04 06:50:03       28 阅读
  5. C语言经典错误总结(二)

    2024-04-04 06:50:03       55 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-04 06:50:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-04 06:50:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-04 06:50:03       82 阅读
  4. Python语言-面向对象

    2024-04-04 06:50:03       91 阅读

热门阅读

  1. 如何开启MySQL的binlog日志

    2024-04-04 06:50:03       34 阅读
  2. Mac 如何彻底卸载Python 环境?

    2024-04-04 06:50:03       39 阅读
  3. ffmpeg Android 笔记

    2024-04-04 06:50:03       37 阅读
  4. springboot如何编写gitlabrunner的部署文件

    2024-04-04 06:50:03       32 阅读
  5. pdf预览组件react-pdf,pdfjs-dist

    2024-04-04 06:50:03       31 阅读