{article Dive into Python}{text} {/article}

The evaluation using the and and or operators follow these rules:

  • and and or evaluates expression from left to right.
  • with and, if all values are True, returns the last evaluated value. If any value is false, returns the first one.
  • or returns the first True value. If all are False, returns the last value

and

>>> 'a' and 'b'
'b'
>>> print ('a' and 'b')
b
>>> 'a' and 'b'
'b'
>>> '' and 'b'
''
>>> 'a' and 'b' and 'c'
'c'
>>>

When using and, values are evaluated in a boolean context from left to right. 0, '', [], (), {}, and
None are false in a boolean context; everything else is true. Well, almost everything. By default,
instances of classes are true in a boolean context, but you can define special methods in your class to
make an instance evaluate to false. You'll learn all about classes and special methods in Chapter 5. If all
values are true in a boolean context, and returns the last value. In this case, and evaluates 'a', which is
true, then 'b', which is true, and returns 'b'.


If any value is false in a boolean context, and returns the first false value. In this case, '' is the first false value.


All values are true, so and returns the last value, 'c'.

or

>>> 'a' or 'b'
'a'
>>> '' or 'b'
'b'
>>> '' or [] or {}
{}
>>> def sidefx():
print ("in sidefx()")
return 1

>>> 'a' or sidefx()
'a'
>>>

When using or, values are evaluated in a boolean context from left to right, just like and. If any value is true,
or returns that value immediately. In this case, 'a' is the first true value.


or evaluates '', which is false, then 'b', which is true, and returns 'b'.


If all values are false, or returns the last value. or evaluates '', which is false, then [], which is false, then
{}, which is false, and returns {}.


Note that or evaluates values only until it finds one that is true in a boolean context, and then it ignores the
rest. This distinction is important if some values can have side effects. Here, the function sidefx is never
called, because or evaluates 'a', which is true, and returns 'a' immediately.

and−or Trick

>>> a = "first"
>>> b = "second"
>>> 1 and a or b
'first'
>>> 0 and a or b
'second'
>>>

This syntax looks similar to the bool ? a : b expression in C. The entire expression is evaluated
from left to right, so the and is evaluated first. 1 and 'first' evalutes to 'first', then
'first' or 'second' evalutes to 'first'.


0 and 'first' evalutes to False, and then 0 or 'second' evaluates to 'second'.