Python3 布尔类型
阅读 (104) |
发布于 2020-05-19 11:43:24
布尔类型即 对于错、0和1、正与反。
在Python语言中,布尔类型只有两个值,True与False。
布尔值通常用来判断条件判断是否成立age = 15
if age >= 18:
print("成年人")
else:
print("未成年人")
python 内置bool()函数可以用来测试一些表达式是否成立。>>> bool("")
False
>>> bool("a")
True
>>> bool(0)
False
>>> bool(1)
True
>>> bool(0.0)
False
>>> bool(-0.0)
False
>>> bool(-0)
False
>>> bool([])
False
>>> bool({})
False
>>> bool(())
False
在python中, 0 -0 0.0 -0.0 空字符 空列表 空字典 空元组 都为False。
布尔类型可以进行and、or和not运算
and 与运算 and前后都为真时为真,and 有一项为假则为假>>> True and True
True
>>> True and False
False
>>> False and False
False
or 或运算 有且至少有一项为真则为真。>>> False or False
False
>>> False or True
True
>>> True or True
True
not 非运算>>> not True
False
>>> not False
True
空值(None)
None 不是布尔型 , 而是 NoneType, 它是一个特殊的值。 我们来看看None用bool() 来判断时:>>> bool(None)
False
脑洞一下
如果我们用布尔型的值做四则运算会怎么样呢?>>> True > False
True
>>> True < False
False
>>> True
True
>>> True > 0
True
>>> True < 0
False
>>> True - 1
0
>>> False - 1
-1
我们发现在python的四则运算中, 把True 看作1 , 而把False看作0.