Python Boolean types

Boolean type in Python

We already know Python supports Boolean data type, Boolean type only Trueand Falsetwo kinds of value, but a Boolean operation are the following:

AND operation : The result of the calculation is True only if both Boolean values are True.

True and True # ==> True
True and False # ==> False
False and True # ==> False
False and False # ==> False

OR operation : As long as there is a Boolean value of True, the result of the calculation is True.

True or True # ==> True
True or False # ==> True
False or True # ==> True
False or False # ==> False

Non-operation : Turn True to False, or False to True:

Not True # ==> False
Not False # ==> True

Boolean operations are used in the computer to make conditional judgments. Depending on whether the result is True or False, the computer can automatically execute different subsequent codes.

In Python, Boolean types can also do and, or, and not operations with other data types. See the following code:

a = True
Print a and 'a=T' or 'a=F'

The result of the calculation is not a boolean type, but a string ‘a=T’. Why?

Because the Python 0空字符串''and Noneas  False , other values and non-empty strings are considered True , so:

True and 'a=T' calculation result is 'a=T'
Continue to calculate 'a=T' or 'a=F' or the result is 'a=T'

To explain the above results, it also involves an important rule of the and and or operations: short-circuit calculation.

1. In calculation a and b , if a is False, then according to the algorithm, the whole result must be False, so return a; if a is True, the whole calculation result must depend on b, so b is returned.

2. In the calculation a or b , if a is True, according to the OR algorithm, the whole calculation result must be True, so return a; if a is False, the whole calculation result must depend on b, so b is returned.

So when the Python interpreter does Boolean operations, as long as the calculation results can be determined in advance, it will not be counted back and return the result directly.

Leave a Reply

Your email address will not be published. Required fields are marked *