【原创】python Boolean/Bool…

5.2. Boolean Operations — andornot

These are the Boolean operations, ordered by ascending priority:

Operation Result Notes
or y if x is false, then y, else x (1)
and y if x is false, then x, else y (2)
not x if x is false, then True, else False (3)

Notes:

  1. This is a short-circuit operator, so it only evaluates the second argument if the first one is False.
  2. This is a short-circuit operator, so it only evaluates the second argument if the first one is True.
  3. not has a lower priority than non-Boolean operators, so not == b is interpreted as not (a == b), and == not b is a 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 ...都可以拼接的的比如 x and y and (a or b and c) ,判断顺序是从左往右,优先执行括号中的噢!本例中的a or b and c = Result会优先判断,然后再判断 x and y and Result

原创所有,转载请附明本文链接,谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值