Using the Boolean operator in Python to do a truth test instance

Source: Internet
Author: User
In Python, any type of object can be tested for truth and is guaranteed to return TRUE or false.

The following values (regardless of type) return False in the truth test:

1.None
2.False
3. Any type of number 0, including 0,0.0,0l,0j
4. Empty sequence (sequence) or map (mapping) Type Object
5. For objects of user-defined type, if their class defines a __nonzero__ () or __len__ () special method and returns false or 0

For the last rule, there are a few things to note:

1. If the class does not have any of these two methods defined, then this type of object truth test is always true
2. If the class defines both __nonzero__ () and __len__ (), only the return value of the __nonzero__ () is referenced

The properties of the Boolean operator (directly from the copy document):

The 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 was false, then True, else false

1. Note the short-circuit characteristics of the and and OR operators
The 2.not operator either returns TRUE or returns False
The return value of the 3.and and or operators is not limited to true and false, it is just a truth test on X or Y, and then returns one of the values (note that it is not the truth)

code example:

The code is as follows:


s = '
s = s or ' default value '
Print S

The operating result is:

The 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.