I used to think that AND and OR operator were only used for judging True or False, but after reading the book Learn Python the hard way, I found one common question in Boolean Practice.
Why does “test” and “test” return “test” or 1 and 1 return 1 instead of True?
This question aroused my interest, can this two operators return other type value?
Therefore, I looked for some documents on the Internet, and noticed that the calculation logic for AND and OR operator.
- AND and OR return the value existed in the boolean expression
- The priority of AND is larger than that of OR
- If all subexpressions in AND operator are all true, and return the last subexpression. Otherwise, return the first subexpression which is False.
- If at least one subexpression in OR operator is True, and then return the first True subexpression. And if all subexpressions in OR operator are false, return the last false subexpression.
In Python, 0,””,[],(),{},None,False are False value and others are True value. According to the calculation process, these two operators can also return other type values, not only True or False.
And why do we often consider that AND and OR can only return True or False? (Such as (a == 3) and (b == 5) )
This is because that the subexpressions in AND and OR this time only includes True and False, and the return only has two options. True and False.
To enhance the understanding for it, I listed some examples as below,
1 | a = 11 and 12 and 13 # a = 13 |
And we may have another question after knowing the calculation logic for AND and OR, how can we do the bitwise operator in Python?
The answer is to use the operator like &, | and ^.
The following is the example.
1 | a = 3 & 5 # a = 1 (011 and 101 = 001) |