4.6. And and or special character
In Python,, and and or perform boolean logic calculus, as you would expect the same. But they do not return a Boolean value, but they return one of the actual value comparison.
Example 4.15. And Introduction
>>> 'a' and 'b'
'b'
>>> '' and 'b' '' >>> 'a' and 'b' and 'c' 'c'
Use and when, from left to right value calculation expression in a boolean context. 0 , '' , [] , () , {} , None of the environment in a boolean false; anything else is true. Fortunately, almost everything. By default, Environment class instance Boolean is true, but you can define a specific class such calculation method of the class instance is false. You will be in Chapter 5 learned about classes and special methods. If all Boolean environments are true, so and returns the last value. In this example, and calculating 'a' is true, then 'b' calculus is true, eventually returns 'b' . | |
If a Boolean value is false environment, then and returns the first false value. In this example, '' is a first false value. | |
All values are true, so and returns the last value true, 'C' . |
Example 4.16. Or introduction
>>> 'a' or 'b'
'a'
>>> '' or 'b' 'b' >>> '' or [] or {} {} >>> def sidefx(): ... print "in sidefx()" ... return 1 >>> 'a' or sidefx() 'a'
If you're a C hacker language must be very familiar with the bool ? A : b expression, if bool is true, the expression evalutes A , otherwise b . Based on Python, and and or work, you can accomplish the same thing.
4.6.1 The use and-or tricks
>>> a = "first"
>>> b = "second"
>>> 1 and a or b 'first' >>> 0 and a or b 'second'
However, since this Python expression only just Boolean logic operations, not the specific language of the constitution, which is and-or tricks and C language BOOL ? A : b very important difference grammar. If a is false, the expression will not work as you expect. (Can you tell I was tossing it over this issue? More than once?)
and-or skill, that is BOOL and a or b expression, when a value is false in a boolean context, and not as the C language expression BOOL ? a : b work as.
In the and-or real trick behind the trick is to ensure that a value is never false. The most common way is to make a be [ a ] , b become [ b ] , then returns the first element of a list of values, should be a or b is one.
Until now, this trick may seem like more trouble than it's worth. After all, using the if statement can accomplish the same thing, so why go through all this fuss? Oh, in many cases, you have to choose between two constant values, because you know that a value is always true, so you can use this simple syntax and not worry. For more complicated safe form, there is good reason to do so. For example, in some cases in Python if statements are not allowed, such as in lambda functions.