python中使用if not x 語句用法
阿新 • • 發佈:2018-11-04
在Python中,None、空列表[]、空字典{}、空元組()、0等一系列代表空和無的物件會被轉換成False。除此之外的其它物件都會被轉化成True。
#!/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')
上面會輸出:
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 有三種表達方式
第一種是`if x is None`;
第二種是 `if not x:`;
第三種是`if not x is None`(這句這樣理解更清晰`if not (x is None)`)
注意:[]不等於None型別,也就是x==[]和x==None
重點看下面例子:
>>> 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