and
and or
work just like the familiar boolean operators - they return true if both of their operands are true and false if one of their operands are true, respectively.
They also short circuit, just like &&
and ||
.
However, in Python, where anything can be interpreted as being True
or False
in a boolean context, there is an additional fact - it will return the first operand that evaluated to True
or evaluated to False
in a boolean context, when it has enough information to stop evaluation. (This is as opposed to constructing and returning a real boolean True
or False
.) This is okay to do because if it is boolean evaluated it will evaluate to the boolean it would have returned if not for this fact.
Thus (note that ""
is evaluated to False
in a boolean context):
>>> "" and "a"
''
>>> "a" and "b"
'b'
>>> "a" and ""
''
>>>
>>> "" or ""
''
>>> "a" or ""
'a'
>>> "" or "a"
'a'
>>> "a" or "b"
'a'
>>> "" or False
False
>>> "" or True
True
>>> False and ""
False