and
and or
are boolean operators and their behaviour is explained in the documentation:
The expression x and y
first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
The expression x or y
first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
If these were functions they would look like (roughly) like this:
def and_function(x, y):
if bool(x) == False: # if x is false, its value is returned
return x
else: # otherwise, y is evaluated and the resulting value is returned
return y
def or_function(x, y):
if bool(x) == True: # if x is true, its value is returned
return x
else: # otherwise, y is evaluated and the resulting value is returned.
return y
So these will always evaluate to either x
or y
, depending on the truth-value of the left side.
In this context "evaluate" refers to the expression not the boolean value. So x or somefunction()
wouldn't evaluate the somefunction()
if bool(x) == True
. That's where the function equivalent fails because these functions don't postpone the evaluation of the expression. So don't take these two functions too seriously. They were only meant as explanation helpers.
The truth-value testing documentation explains how the truth-value of numbers is defined:
[...] The following values are considered false:
False
zero of any numeric type, for example, 0, 0.0, 0j.
[...]
All other values are considered true — so objects of many types are always true.
Then you asked about equality between the booleans True
and False
and numbers. To understand this you have to know that bools are a subclass of integers in Python. In some sense True
is just another name for 1
and False
for 0
. So it's not surprising that True == 1
and False == 0
are both True
.
NB: If you come from other languages it might be important to state that there is no implicit casting for comparisons in Python, I explained this in another answer in more details: "Why does … == True return False?".