您的位置:首页 > 编程语言 > Python开发

Python内置类型(2)——布尔运算

2017-10-13 14:15 176 查看


python中bool运算符按优先级顺序分别有
or
and
not
, 其中
or
and
为短路运算符


not
先对表达式进行真值测试后再取反

not
运算符值只有1个表达式,
not
先对表达式进行真值测试后再取反,返回的结果不是
True
就是
False


>>> expression1 = ''
>>> expression2 = '1'
>>> not expression1
True
>>> not expression2
False


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 : 2
True

>>> is_even(1) or is_even(2)
input num is : 1
input num is : 2
True

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 : 1
False

# 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 : 1
this num is : 5
False

not
运算符的优先级比
or
and
高,一起使用的时候,会先计算
not
,再计算
or
and
的值

>>> is_even(1) or is_even(3)
this num is : 1
this num is : 3
False
>>> not is_even(1) or is_even(3)
this num is : 1
True
>>> is_even(1) or not is_even(3)
this num is : 1
this num is : 3
True
>>>

not
运算符的优先级比
==
!=
低,
not a == b
会被解释为
not (a == b)
, 但是
a == not b
会提示语法错误。

>>> not 1 == 1
False
>>> 1 == not 1
SyntaxError: invalid syntax
>>> not 1 != 1
True
>>> 1 != not 1
SyntaxError: invalid syntax

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: