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

Source: Internet
Author: User

In Python, objects of any type can be tested for truth values and are 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 mapping (mapping) Type objects
5. For objects of user-defined types, if their classes define __NONZERO__ () or __len__ () special methods and return False or 0

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

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

The attributes of the Boolean operator (direct copy document):

Copy Code code 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. 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 simply does a truth test on X or Y, and then returns one of the values (note that it is not its truth)

code example:

Copy Code code as follows:

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

The results of the operation are:

Copy Code code 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.