今天在网站上学习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: False, None, 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.