Python Boolean and PythonBoolean operations
In Python, any type of object can be used for True value testing and True or False is returned.
The following values (regardless of the type) return False in the true value test:
1. None
2. False
3. Any type of numbers 0, including 0, 0.0, 0L, 0j
4. Empty sequence or mapping objects
5. for user-defined objects, if the class defines_ Nonzero __()Or_ Len _ () special method and return False or 0
For the last rule, there are several points to note:
1. If the class does not define any of the two methods, the True value of this type of object is always True during testing.
2. If the class is defined at the same time_ Nonzero __()And_ Len _ (). Only the return values of _ nonzero _ () are referenced.
Features of the Boolean operator (directly from the copy document ):
X or y: if x is false, then y, else x
X and y: if x is false, then x, else y
Not x: if x is false, thenTrue, ElseFalse
1. Pay attention to the short circuit feature of the and or operators.
2. The not operator either returns True or False.
3. The return values of the and or operators are not limited to True and False. They only test the True value of x or y and return a value (note that it is not the True value)
Sample Code:
s = ''s = s or 'default value'print s
The running result is:
Default value