Python Boolean and PythonBoolean operations

Source: Internet
Author: User

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

Related Article

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