In Python, and and or to perform Boolean logic calculations, as you would expect, but they do not return Boolean values, but instead return one of the values they actually compare.
One, and:
>>> ' A ' and ' B ' B ' >>> ' and ' B ' ' >>> ' a ' and ' B ' and ' C '
The value of a left-to-right calculus expression in a Boolean context, and returns the last value if all the values in the Boolean context are true.
If a value in the Boolean context is false, and returns the first false value
Second, or:
>>> ' A ' or ' B ' a ' >>> ' or ' B ' b ' >>> ' or [] or {}{}>>> 0 or ' a ' or ' C ' a '
When using or, the left-to-right calculus is evaluated in a Boolean context, just like and. If a value is true, or returns the value immediately
If all values are false, or returns the last False value
Note that or in a Boolean context, the expression calculus continues until the first true value is found, and then the remaining comparison values are ignored
Third, And-or:
And-or combines the two preceding syntaxes, reasoning can be.
>>> a= ' first ' >>> b= ' second ' >>> 1 and A or B ' first ' >>> (1 and a) or B ' first ' >>> ; 0 and A or B ' second ' >>> (0 and a) or B ' second ' >>>
Does this syntax look similar to bool in C? An A:B expression. The entire expression is left-to-right, so the calculation of the and expression is performed first. The 1 and ' first ' calculation is ' first ', then ' first ' or ' second ' is ' first ' calculation value.
0 and ' first ' calculation value is False, then 0 or ' second ' calculus value is ' second '.
And-or is mainly used to mimic the bool?a:b of the trinocular operator, that is, when the expression bool is true, take a otherwise take B.
And-or techniques, bool and A or B expressions, when a value in a Boolean context is false, does not resemble a C-language expression bool? A:B work like that.
Iv. Safe use of and-or
>>> a= "" >>> b= "Second" >>> (1 and [a] or [b]) [']>>> (1 and [a] or [b]) [0] ' >>> ;
Because [a] is a non-empty list, it is never false. Even if a is 0 or ' or other false values, the list [a] is also true because it has an element.
A responsible programmer should encapsulate the and-or technique into a function:
def choose (bool,a,b): return (BOOL and [a] or [b]) [0]print Choose (1, ', ' second ') # '