We've learned that Python supports Boolean types of data, with only a Boolean type True
and False
two values, but the Boolean type has the following operations:
and operation: Only two Boolean values are true when the result is true.
True and True # ==> Truetrue and False # ==> Falsefalse and True # ==> Falsefalse and False # ==& Gt False
Or operation: evaluates to true as long as there is a Boolean value of true.
True or True # ==> truetrue or False # ==> TrueFalse or True # ==> TrueFalse or False # ==> Fa Lse
Non-operation: Turns true to false, or false to true:
Not True # ==> falsenot False # ==> True
Boolean operations are used in a computer to make conditional judgments, and the computer can automatically execute different follow-up code, depending on the result of the calculation as true or false.
In Python, Boolean types can also do and, or, and not with other data types, see the following code:
A = Trueprint A and ' a=t ' or ' a=f '
The result of the calculation is not a Boolean type, but the string ' a=t ', which is why?
Because Python regards 0
, 空字符串‘‘
and None
is treated as False, other numeric values and non-empty strings are considered True, so:
True and ' a=t ' evaluates to ' a=t ' continue to calculate ' a=t ' or ' a=f ' results or ' a=t '
To explain the above results, it also involves an important law of the and and or operations: short-circuit calculation.
1. In the calculation a and b
, if A is false, then according to the algorithm, the whole result must be false, so it returns a; If A is True, the entire result must depend on B, and therefore returns B.
2. In the calculation a or b
, if A is true, the whole result must be true, according to the or algorithm, and therefore return a; If A is False, the whole result must depend on B, and therefore return B.
So when the Python interpreter is doing a Boolean operation, as long as the calculation results can be determined in advance, it will not go back and return the result directly.
Boolean type in Python