Python uses the Boolean operator to test the true value.
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 the special _ nonzero _ () or _ len _ () methods and returns 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 Classes define both _ nonzero _ () and _ len _ (), only the return values of _ nonzero _ () are referenced.
Features of the Boolean operator (directly from the copy document ):
Copy codeThe Code is as follows:
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, then True, else False
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:
Copy codeThe Code is as follows:
S =''
S = s or 'default value'
Print s
The running result is:
Copy codeThe Code is as follows:
Default value