Python中Boolean operator的一些特点

今天在网站上学习Learn Python The Hard Way,Exercise 28(http://learnpythonthehardway.org/book/ex28.html)时,[Common Student Questions] 有个问题引起了我的兴趣Why does "test" and "test" return "test" or 1 and 1 return 1 instead of True?

作者的回答是:Python and many languages like it return one of the operands to their boolean expressions rather than just True or False. This means that if you did False and 1 you get the first operand (False) but if you do True and 1 your get the second (1). Play with this a bit.

相比于这个回答,官方文档的解释则更清晰http://docs.python.org/2/reference/expressions.html#and

—————————————————————————————————————————————————————————

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: FalseNone, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. (See the __nonzero__() special method for a way to change this.)

The operator not yields True if its argument is false, False otherwise.

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

(Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or 'foo'yields the desired value. Because not has to invent a value anyway, it does not bother to return a value of the same type as its argument, so e.g., not 'foo' yields False, not ''.)

—————————————————————————————————————————————————————————

针对上面的描述,我们可以得出以下结论:

1.若False是第一个操作数,则False and * ,无论 * 是什么,运算式的值是False

2.若True是第一个操作数,则True or * ,无论*是什么,运算式的值是True

结论1,2实际就是逻辑运算符的短路求值(Short-circuit evaluation)策略


递进一下:

3.若第一个操作数X1是“逻辑假”的,那么X1 and *,无论*是什么,运算式的值就是X1

例如:[] and True 的值为[]

4.若第一个操作数X1是“逻辑真”的,那么X1 or *,无论*是什么,运算式的值就是X1

例如:'Test' or False 的值为'Test'

结论3,4 说明and/or 运算式值不会只有True和False


最终结论:

Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值