The operator and
treats your operands as boolean. That is, when you do:
5 and 6
The Python interpreter will do the cast from operands to bool
and then check the result. Something like bool(5) and bool(6)
, but not quite that. What actually happens has to do with short-circuiting in logical expressions. That is, Python will check the first operand by checking the result of bool(5)
; if true and the operation is and
, the final result will depend only on the second operand, this being returned, because True and X
will always be X
, independent of its value. If you change the operator to or
, that is, do 5 or 6
, the same logic occurs, however, as bool(5)
is treated as true, the short circuit of the expression happens and is returned the value 5, because True or X
is always true, independent of X
.
The logic you described expecting the result 4 is known as bit-by-bit logic. To do so, you will need to use the operator &
for bitwise and
or |
for bitwise or
. That is, the result 4, which is expected, can be obtained by:
print(5 & 6)
Or value 7 when doing print(5 | 6)
, for 101 | 110
results in 111
.
To complete the reply of the LINQ, which in turn supplements this, the equivalent (unofficial) code of the operator and
is:
def _and_ (x, y):
# Interpreta o valor de x como booleano:
eval_x = bool(x)
# Se for falso:
if not eval_x:
# Retorna o valor de x:
return x
# Caso contrário, retorna y:
return y
If you do print(5 and 6 == _and_(5, 6))
you’ll see that the exit is True
.
Already to the operator or
:
def _or_ (x, y):
# Interpreta o valor de x como booleano:
eval_x = bool(x)
# Se for verdadeiro:
if eval_x:
# Retorna o valor de x:
return x
# Caso contrário, retorna y:
return y
As commented on the above-mentioned answer, the return of the operator is not necessarily of the boolean type, because the returned values are x
or y
, and in this way, the returned type will be the type of x
or of y
, depending on which one was returned by the operator. Fact that can be proven by making print(type(5 and 6))
, resulting in <class 'int'>
, or print(type([] and 6))
which results in <class 'list'>
.
The logical operator
and
is different from&
, who is the operator and bit by bit. If you doprint(5 & 6)
, the output will be 4 as expected.– Woss