Reputation: 3233
Why does '' and not '123'
evaluate to ''
instead of False
, but not '123' and ''
evaluates to False
in Python 3.4.3?
Upvotes: 2
Views: 227
Reputation: 113964
The logical and/or operators stop evaluating terms (short-circuit) as soon as the answer is decided.
and
>>> '' and not '123'
''
The first one is false, so the and
is short-circuited and the first one is returned.
>>> not '123' and ''
False
not '123'
returns False
. Since that is false, the and
is short-circuited and the result of not '123'
one is returned.
For exactly the same reason, the following returns zero:
>>> 0 and '123'
0
And the following returns []
:
>>> [] and '123'
[]
or
>>> '' or '123'
'123'
>>> not '123' or 'Hi'
'Hi'
>>> '123' or 'Hi'
'123'
This behavior is specified in the documentation where:
x or y
is defined as if x is false, then y, else x
x and y
is defined as if x is false, then x, else y
not x
is defined as if x is false, then True, else False
Upvotes: 2