The and
operator treats its operands as booleans. This is when you do:
5 and 6
The Python interpreter will cast the cast of the operands to bool
and then check the result. Something like bool(5) and bool(6)
, but not exactly that. What happens in fact is related to the short circuit in logical expressions. That is, Python will check the first operand, checking the result of bool(5)
; if true and the operation is and
, the final result will depend only on the second operand, which is returned, since True and X
will always X
, regardless of its value. If you change the operator to or
, that is, to 5 or 6
, the same logic occurs, however, since bool(5)
is treated as true, the expression short circuit happens and the value 5 is returned because True or X
is always true, independent of X
.
The logic you described expecting output 4 is known as bitwise logic. To do this, you must use the &
operator for bitwise and
or |
to bitwise or
. That is, the result 4, which is expected, can be obtained by doing:
print(5 & 6)
Or the value 7 when doing print(5 | 6)
, because 101 | 110
results in 111
.
To complete LINQ's response , which in turn completes that, the equivalent (unofficial) of the and
operator 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 will see that the output is True
.
Already for the or
operator:
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 response, the return of the operator is not necessarily of the Boolean type, since the returned values are x
or y
, and thus the returned type will be the type of x
or y
, depending on which was returned by the operator. This fact can be proven by doing print(type(5 and 6))
, resulting in <class 'int'>
, or print(type([] and 6))
which results in <class 'list'>
.