String comparison gotcha

Question Q2.3.5

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

Solution

To access solutions, please obtain an access code from Cambridge University Press at the Lecturer Resources page for my book (registration required) and then sign up to scipython.com providing this code.