布尔值是“真”True或“假”False中的一个
注:首字母必须大写T、F;Python代码输入时,布尔值True和False不同于字符串,两边没有引号
在程序中,求值为真,则可继续运行下去;求值为假,条件不成立,将跳过此代码块,进入下一步的运行
如:
message=True
message
True
True
True
true
Traceback (most recent call last):
File "", line 1, in
true
NameError: name 'true' is not defined. Did you mean: 'True'?
True=2+2
SyntaxError: cannot assign to True
布尔值也可保存在表达式中的变量中
如果试图使用True和False作为变量名,或者大小写不正确,程序将会报错error
1、 and
2、 or
3、 not
二元布尔操作符(and和or):因其接受两个布尔值(或表达式),故被称为“二元”操作符
1、and 操作符
如两个布尔值都为True,and操作符就将布尔值或表达式求值为True,否则求值为False
True and True
True
True and False
False
2、or 操作符
如果两个布尔值有一个或者两个为True,or操作符就将布尔值或表达式求值为True,否则求值为False
如:
True or True
True
True or False
True
False or False
False
3、not 操作符
not操作符只用作一个布尔值或表达式,求值为相反的布尔值
如:
not True
False
not False
True
and、or和not操作符称为布尔操作符是因为操作于布尔值
虽然6<12表达式不是布尔值,但可求值为布尔值
如:
(6<12) and (17<25)
True
(7<8) and (21<19)
False
(8==8) or (9==10)
True
程序将先求值左边的表达式,再求值右边的表达式,得到两个布尔值后,又将整个表达式再求值为一个布尔值
也可在一个表达式中使用多个布尔操作符,与比较操作符一起使用
如:
6+7==12 and not 11+11==22 and 8*9==36+36
False
6+7==12 and not 11+11==22 or 8*9==36+36
True
和算术操作符一样,布尔操作符也有操作顺序,在所有算术和比较操作符求值后,先求not操作符,然后再求and操作符,然后再求or操作符
留言与评论(共有 0 条评论) “” |