【原创】python Boolean/Bool…

来源:互联网 发布:动态制作软件 编辑:程序博客网 时间:2024/05/10 20:06

5.2. Boolean Operations — andornot

These are the Boolean operations, ordered by ascendingpriority:

OperationResultNotesx or yif x is false,then y,else x(1)x and yif x is false,then x,else y(2)not xif x is false,then True,else False(3)

Notes:

  1. This is ashort-circuit operator, so it only evaluates the second argument ifthe first one is False.
  2. This is ashort-circuit operator, so it only evaluates the second argument ifthe first one is True.
  3. not has a lower priority thannon-Boolean operators, so not a == b isinterpreted as not (a == b),and a == not b isa syntax error.
以上是python官方学习文档的解释,下面做几个小例子说明一下。

1.x and y:
Ex:
>>>1 and 2
2
>>> 1 and 0
0
>>> 0 and 1
0
【释】依次找False值,找到就输出第一个False值,若到结尾还没False值,就输出最后一个True值。
2.x or y :
Ex:
>>>1 or 2
1
>>>0 or 1
1
>>>0 or 0
0
>>>0 or 1 or 3
1
>>>{} or 0 or []
[]
【释】依次找True值,找到就输出第一个True值,若到结尾还没有True值,就输出最后一个False值。

3. not
>>>not -1
False
>>> not 0
True
>>> not 1
False
>>> not 2
False
>>> not []
True
>>> not('')
True
【释】这就是所谓的负负得正(负指的是False,所有为空、零,("")为True值,元组中有一个空元素,元组不为空,所以为真值)

当然啦,and or not ...都可以拼接的的比如 xand y and (a or b and c) ,判断顺序是从左往右,优先执行括号中的噢!本例中的a or b and c =Result会优先判断,然后再判断 x and y and Result

原创所有,转载请附明本文链接,谢谢!
http://blog.sina.com.cn/s/blog_83dc494d0101bc6z.html

0 0