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

来源:互联网 发布:易宝软件深圳分公司 编辑:程序博客网 时间:2024/06/10 16:50

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

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

>>> expression1 = ''>>> expression2 = '1'>>> not expression1True>>> not expression2False

orand运算符返回的结果是操作符两边的表达式中的符合逻辑条件的其中一个表达式的结果

在其它语言中,比如C#,bool运算的结果肯定也是bool值;但是python中不是这样的,它返回的是满足bool运算条件的其中一个表达式的值。

  • x or y

若 xTrue,则结果为x;若xFalse, 则结果为y

>>> expression1 = '1'>>> expression2 = '2'>>> expression1 or expression2'1'>>> expression2 or expression1'2'
  • x and y

若 xFalse,则结果为x;若xTrue, 则结果为y

>>> expression1 = ''>>> expression2 = {}>>> expression1 and expression2''>>> expression2 and expression1{}

orand运算符是短路运算符

短路运算符的意思是,运算符左右的表达式的只有在需要求值的时候才进行求值。比如说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

orand运算符可以多个组合使用,使用的时候将以此从左到右进行短路求值,最后输入结果

表达式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运算符的优先级比orand高,一起使用的时候,会先计算not,再计算orand的值

>>> 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