布尔类型
来源:互联网 发布:众筹软件排名 编辑:程序博客网 时间:2024/05/01 00:48
布尔类型
运行结果:我们已经了解了Python支持布尔类型的数据,布尔类型只有
True
和False
两种值,但是布尔类型有以下几种运算:与运算:只有两个布尔值都为 True 时,计算结果才为 True。
True and True # ==> TrueTrue and False # ==> FalseFalse and True # ==> FalseFalse and False # ==> False或运算:只要有一个布尔值为 True,计算结果就是 True。
True or True # ==> TrueTrue or False # ==> TrueFalse or True # ==> TrueFalse or False # ==> False非运算:把True变为False,或者把False变为True:
not True # ==> Falsenot False # ==> True布尔运算在计算机中用来做条件判断,根据计算结果为True或者False,计算机可以自动执行不同的后续代码。
在Python中,布尔类型还可以与其他数据类型做 and、or和not运算,请看下面的代码:
a = Trueprint a and 'a=T' or 'a=F'计算结果不是布尔类型,而是字符串 'a=T',这是为什么呢?
因为Python把
0
、空字符串''
和None
看成 False,其他数值和非空字符串都看成 True,所以:True and 'a=T' 计算结果是 'a=T'继续计算 'a=T' or 'a=F' 计算结果还是 'a=T'要解释上述结果,又涉及到 and 和 or 运算的一条重要法则:短路计算。
1. 在计算
a and b
时,如果 a 是 False,则根据与运算法则,整个结果必定为 False,因此返回 a;如果 a 是 True,则整个计算结果必定取决与 b,因此返回 b。2. 在计算
a or b
时,如果 a 是 True,则根据或运算法则,整个计算结果必定为 True,因此返回 a;如果 a 是 False,则整个计算结果必定取决于 b,因此返回 b。所以Python解释器在做布尔运算时,只要能提前确定计算结果,它就不会往后算了,直接返回结果。
任务
请运行如下代码,并解释打印的结果:
a = 'python'print 'hello,', a or 'world'b = ''print 'hello,', b or 'world'
hello, pythonhello, world
0 0
- 布尔类型
- 布尔类型
- 布尔类型
- 布尔类型
- 布尔类型
- Delphi中的布尔类型
- C++中布尔类型
- Oracle 实现布尔类型
- C#布尔类型
- javascript 布尔类型
- C#布尔类型
- 布尔类型判断-python
- C中的布尔类型
- 2.3布尔类型
- python 布尔类型
- python1:布尔类型
- 8. PHP 布尔类型
- 布尔类型探究
- leetcode:Course Schedule II
- 特征闭包的三个
- 1006. 换个格式输出整数 (15)——做题纪录
- Android三星手机拍照自动旋转问题解决方案
- 七牛---JavaScript多按钮上传
- 布尔类型
- 第6周-项目2-带武器的游戏角色
- bzoj 4384: [POI2015]Trzy wieże 树状数组
- [GDOI模拟04.02总结]
- Application Performance Management工具之pinpoint
- 备忘录模式
- Linux _TCP 浅解
- 神经网络入门(连载之三)
- 项目4 长方柱类