真值测试
在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的范围内,则提示出错
