肉渣教程

布尔型

上一节 下一节

布尔型(Boolean)

布尔型(bool)就两个值,分别是TrueFalse;分别代表是与非。主要是用在选择语句中,True代表肯定,False代表否定;条件成立则返回True,条件不成立则放回False。多说无益,看例子:

>>> a = True
>>> if a:
...     print "yes"
... else:
...     print "no"
... 
yes
>>> b = False
>>> if b:
...     print "yes"
... else:
...     print "no"
... 
no

运行一下


如下所示,条件表达式返回的值就是True或False:

>>> 1 == 2
False
>>> 1 < 2
True

运行一下

布尔运算符

布尔运算符只有三种:notandor;其中not的优先级最高,and次之,or垫底。

其中not是一元运算符,只需后面对应跟上一个值即可。对于含有not的表达式,如果原始值是False,结果则为True;若原始值是True,则结果为False。示例如下:

>>> not True
False
>>> not False
True

运行一下


and符号是二元运算符,只有and两侧均为True,结果才为True;否则返回的都是False。示例如下:

>>> True and True
True
>>> True and False
False
>>> False and True
False
>>> False and False
False

运行一下


or符号也是二元运算符,只要or两侧有一个为True,则结果就可以为True;若两侧没有一个为True,则返回False。示例如下:

>>> True or True
True
>>> True or False
True
>>> False or True
True
>>> False or False
False

运行一下


对于布尔运算符的复合使用,容易出现歧义,故而请善用小括号,如下所示:

>>> a = True
>>> b = False
>>> not ( a and b )
True
>>> ( not a ) and b
False

运行一下


布尔型

上一节 下一节