前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python中使用if not x 语句

python中使用if not x 语句

作者头像
py3study
发布2020-01-06 15:32:34
1.2K0
发布2020-01-06 15:32:34
举报
文章被收录于专栏:python3python3

在Python中,None、空列表[]、空字典{}、空元组()、0等一系列代表空和无的对象会被转换成False。除此之外的其它对象都会被转化成True。

代码语言:javascript
复制
#!/usr/bin/python
# -*- coding: UTF-8 -*-

######测试if not########
x=0
#x='aa'
#x=[]

if x is None:
	print("x in None!")
	
if not x:
	print('not x!')
	
if not x is None:
	print('not x is None!')
	
if x is not None:
	print('x is not None!')
	
y=1

if y is not None:
	print('y is not None!')

if not y:
	print('not y')

上面会输出:

代码语言:javascript
复制
not x!
not x is None!
x is not None!
y is not None!

看下面代码

代码语言:javascript
复制
>>> x=0
>>> not x
True
>>> x is not None
True
>>> not x is None
True
>>> 
>>> 
>>> x=156
>>> not x
False
>>> x is not None
True
>>> not x is None
True
>>> 
>>>

if not 有三种表达方式

第一种是`if x is None`; 第二种是 `if not x:`; 第三种是`if not x is None`(这句这样理解更清晰`if not (x is None)`) 

注意:[]不等于None类型,也就是x==[]和x==None

重点看下面例子:

代码语言:javascript
复制
>>> x=[]
>>> y=''
>>> z=0
>>> w=None
>>> x is None
False
>>> y is None
False
>>> z is None
False
>>> w is None
True
>>> not x
True
>>> not y
True
>>> not z
True
>>> not w
True
>>> not x is None
True
>>> not y is None
True
>>> not z is None
True
>>> not z is None
True
>>> not w is None
False
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档