Python内置类型(2)——布尔运算
来源:互联网 发布:易宝软件深圳分公司 编辑:程序博客网 时间:2024/06/10 16:50
not
先对表达式进行真值测试后再取反
not
运算符值只有1个表达式,not
先对表达式进行真值测试后再取反,返回的结果不是True
就是False
>>> expression1 = ''>>> expression2 = '1'>>> not expression1True>>> not expression2False
or
、and
运算符返回的结果是操作符两边的表达式中的符合逻辑条件的其中一个表达式的结果
在其它语言中,比如C#,bool运算的结果肯定也是bool值;但是python中不是这样的,它返回的是满足bool运算条件的其中一个表达式的值。
x or y
:
若 x
为True
,则结果为x
;若x
为False
, 则结果为y
。
>>> expression1 = '1'>>> expression2 = '2'>>> expression1 or expression2'1'>>> expression2 or expression1'2'
x and y
:
若 x
为False
,则结果为x
;若x
为True
, 则结果为y
。
>>> expression1 = ''>>> expression2 = {}>>> expression1 and expression2''>>> expression2 and expression1{}
or
、and
运算符是短路运算符
短路运算符的意思是,运算符左右的表达式的只有在需要求值的时候才进行求值。比如说x or y
,python从左到右进行求值,先对表达式x
的进行真值测试,如果表达式x
是真值,根据or
运算符的特性,不管y
表达式的bool结果是什么,运算符的结果都是表达式x
,所以表达式y
不会进行求值。这种行为被称之为短路特性。
#函数功能判断一个数字是否是偶数def is_even(num): print('input num is :',num) return num % 2 == 0#is_even(1)被短路,不会执行>>> is_even(2) or is_even(1)input num is : 2True>>> is_even(1) or is_even(2)input num is : 1input num is : 2True
or
、and
运算符可以多个组合使用,使用的时候将以此从左到右进行短路求值,最后输入结果
表达式x or y and z
,会先对x or y
进行求值,然后求值的结果再和z
进行求值,求值过程中依然遵循短路原则。
#is_even(2)、is_even(4)均被短路>>> is_even(1) and is_even(2) and is_even(4)this num is : 1False# is_even(1)为False,is_even(3)被短路# is_even(1) and is_even(3)为False,is_even(5)需要求值# is_even(1) and is_even(3) or is_even(5)为False,is_even(7)被短路>>> is_even(1) and is_even(3) or is_even(5) and is_even(7)this num is : 1this num is : 5False
not
运算符的优先级比or
、and
高,一起使用的时候,会先计算not
,再计算or
、and
的值
>>> is_even(1) or is_even(3)this num is : 1this num is : 3False>>> not is_even(1) or is_even(3)this num is : 1True>>> is_even(1) or not is_even(3)this num is : 1this num is : 3True>>>
not
运算符的优先级比==
、!=
低,not a == b
会被解释为 not (a == b)
, 但是a == not b
会提示语法错误。
>>> not 1 == 1False>>> 1 == not 1SyntaxError: invalid syntax>>> not 1 != 1True>>> 1 != not 1SyntaxError: invalid syntax
阅读全文
0 0
- Python内置类型(2)——布尔运算
- python——内置类型——整型 浮点型 字符串 布尔型 空型
- WEB前端 | JS基础——(2)布尔类型和关系运算符
- python-布尔运算
- python语法、变量、内置类型、运算符
- 布尔类型判断-python
- python 布尔类型
- Python中的布尔类型
- Python中布尔类型
- Python中的布尔类型
- Python中布尔类型
- Python中布尔类型
- Python中布尔类型
- Python (布尔类型计算)
- c——运算符——内置类型
- swift——运算符——内置类型
- VTK中的布尔运算——vtkBooleanOperationPolyDataFilter
- Objective-C学习——布尔类型
- 文件批量重命名
- 飞凌 飞思卡尔imx6Q交叉编译器的安装
- tensorflow学习三:通过mnist来理解深层神经网络的及优化问题
- Python 多线程,主线程与子线程
- IMS/SIP
- Python内置类型(2)——布尔运算
- iOS中如何实现单个页面支持横竖屏(其他页面只能竖屏)
- imposm.parser
- 生成无重复随机token
- eclipse无法查看源码的解决方案
- angular 获取json字符串
- Linux下php安装Redis扩展
- 三种技术对应的商业模式 – 抢夺IoT市场 三大技术上演争霸赛
- hibernate代理实现懒加载+cglib和jdk动态代理