Consider the following (incorrect) tests to see if string s
has one of two values. Explain how these statements are interpreted by Python and give a correct alternative.
>>> s = 'eggs'
>>> s == ('eggs' or 'ham')
True
>>> s == ('ham' or 'eggs')
False
This is not the correct way to test if the string s
is equal to either 'ham'
or 'eggs'
. The expression ('eggs' or 'ham')
is a boolean one in which both arguments, being non-empty strings, evaluate to True
. The expression short-circuits at the first True
equivalent and this operand is returned: that is, ('eggs' or 'ham')
returns 'eggs'
. Since, s
is, indeed, the string 'eggs'
the equality comparison returns True
. However, if the order of the operands is swapped, the boolean or
again short-circuits at the first True
-equivalent, which is now 'ham'
and returns it. The equality comparison with s
fails, and the result is False
.
There are two correct ways to test if s
is one of two or more strings:
>>> s = 'eggs'
>>> s == 'ham' or s == 'eggs'
True
>>> s in ('ham', 'eggs')
True
(See Section 2.4.2 of the book for more information about the syntax of the second statement).