Python uses the Boolean operator to test the true value.

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.