真值測試
在Python中:
- 任何非零數字或非空對象都為真
- 數字零、空對象以及特殊對象None都被認作是假
- 比較和相等測試會遞歸地應用在數據結構中
- 比較和相等測試會返回True或False(1和0的特殊版本)
- 布爾and和or運算符會返回真或假的操作對象
Python中有三種布爾表達式運算符:
- X and Y
- X or Y
- not X
布爾非操作 not
語法:
not x
作用
對 x 進行布爾取非
如bool(x) 為True,則返回False ...
示例:
not True # False
not False # True
not 100 # False
not not 100 # True
布爾與操作 and
語法:
x and y
注:x,y 代表表達式
作用:
優先返回假值對象
當x的布爾值為False時,返回x否則返回y
示例:
True and True # True
True and False # False
False and True # False
False and False # False
a = 100
b = 200
a and b
布爾或操作 or
語法:
x or y
作用:
優先返回真值對象
當x為True時,返回x,否則返回y
示例:
True or True # True
True or False # True
False or True # True
False or False # False
100 or 200 # 100
100 or 0 # 100
0 or 200 # 200
0 or 0.0 # 0.0
示例:輸入一個學生的成績,
如果成績不在0~100的范圍內,則提示出錯