0%

AND and OR operator in Python

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.

  1. AND and OR return the value existed in the boolean expression
  2. The priority of AND is larger than that of OR
  3. If all subexpressions in AND operator are all true, and return the last subexpression. Otherwise, return the first subexpression which is False.
  4. 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
2
3
4
5
6
7
8
a = 11 and 12 and 13  # a = 13  
b = [] and 3 # b = []
c = None and 3 # c Not any output(None)
d = 3 and 5 or 2 # d = 5
e = 20 or False # e = 20
f = (3 < 2) and 5 # f = False
g = (3 > 2) and 5 or 1 # g = 5
h = (3 < 2) and 5 or 1 # h = 1

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
2
3
a = 3 & 5  # a = 1 (011 and 101 = 001)  
b = 6 ^ 2 # b = 4 (110 xor 010 = 100)
c = 4 | 3 # c = 7 (100 or 011 = 111)