Python中布尔类型
来源:互联网 发布:李刚疯狂java讲义 编辑:程序博客网 时间:2024/05/18 01:42
Python中布尔类型
我们已经了解了Python支持布尔类型的数据,布尔类型只有True和False两种值,但是布尔类型有以下几种运算:
与运算:只有两个布尔值都为 True 时,计算结果才为 True。
True and True # ==> True
True and False # ==> False
False and True # ==> False
False and False # ==> False
或运算:只要有一个布尔值为 True,计算结果就是 True。
True or True # ==> True
True or False # ==> True
False or True # ==> True
False or False # ==> False
非运算:把True变为False,或者把False变为True:
not True # ==> False
not False # ==> True
布尔运算在计算机中用来做条件判断,根据计算结果为True或者False,计算机可以自动执行不同的后续代码。
在Python中,布尔类型还可以与其他数据类型做 and、or和not运算,请看下面的代码:
a = True
print 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 运算的一条重要法则:短路计算。
在计算 a and b 时,如果 a 是 False,则根据与运算法则,整个结果必定为 False,因此返回 a;如果 a 是 True,则整个计算结果必定取决与 b,因此返回 b。
在计算 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, python
hello, world
- Python中布尔类型
- Python中布尔类型
- Python中布尔类型
- Python中布尔类型
- Python中布尔类型 短路计算原理
- 布尔类型判断-python
- python 布尔类型
- Python中的布尔类型
- Python中的布尔类型
- Python (布尔类型计算)
- C++中布尔类型
- C++中布尔类型
- Python中进行布尔类型处理时的特殊点
- Delphi中布尔类型辨析
- Delphi中布尔类型辨析
- Delphi中布尔类型辨析
- Python数据类型(一):数值布尔类型
- 每天学点Python之布尔类型
- 【WebService】快速构建WebService示例
- leetcode(310). Minimum Height Trees
- C#创建Windows服务与安装-图解
- HDU 6166 Senior Pan spfa(顶点集间最短路)
- 1864: [Zjoi2006]三色二叉树
- Python中布尔类型
- 8月23日小结
- 为什么不能通过返回值类型区分重载?
- 模板
- USACO最长前缀(trie练习题)
- 【Zookeeper】概述
- linux总结笔记(一)linux/ubuntu下ping www.baidu.com失败总结(校园网)
- [Leetcode] 365. Water and Jug Problem 解题报告
- 设计模式——单例模式(php)