[Tutor] Coding

Steven D'Aprano steve at pearwood.info
Mon Dec 8 03:24:09 CET 2014

On Mon, Dec 08, 2014 at 01:47:39AM +0000, Alan Gauld wrote:

> > FirstChoice = input ("Enter the item of your choice: ")
> > if FirstChoice == 'Coke' or 'Pepsi' or 'Water':
> >    print ("That will be a total of £",drinks)
> The or statements don't do what you think.
> Python sees it like:
> if FirstChoice == ('Coke' or 'Pepsi' or 'Water'):
> So evaluates the bit in parens first which results in a boolean value of 
> True.

Actually it sees it as:

if ((FirstChoice == 'Coke') or 'Pepsi' or 'Water'):

which will always evaluate as True.

*Technically* it will evaluate as either True or 'Pepsi', which is a 
truthy value, so the if block will always run.

What we actually want is one of these:

# The long way
if (FirstChoice == 'Coke') or (FirstChoice == 'Pepsi') or (FirstChoice == 'Water'):

# The short way
if FirstChoice in ('Coke', 'Pepsi', 'Water'):


More information about the Tutor mailing list