python中使用if not x 語句用法


在Python中,None、空列表[]、空字典{}、空元組()、0等一系列表明空和無的對象會被轉換成False。除此以外的其它對象都會被轉化成True。python


#!/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')

上面會輸出:ide

not x!
not x is None!
x is not None!
y is not None!

看下面代碼
測試

>>> 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 有三種表達方式spa

第一種是`if x is None`;
第二種是 `if not x:`;
第三種是`if not x is None`(這句這樣理解更清晰`if not (x is None)`) 對象

注意:[]不等於None類型,也就是x==[]和x==Noneit

重點看下面例子:class

>>> 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
相關文章
相關標籤/搜索