[Tutor] How to handle conjunction operators

Steven D'Aprano steve at pearwood.info
Mon Nov 28 12:30:06 CET 2011


Timo wrote:

>> if name[0] in ("m", "f", "b"):
> Or even shorter:
> if name[0] in "mfb":

Shorter, but wrong.

name = ['fb', 'ph', 'xy']  # oops, bad data
if name[0] in 'mfb':
     ...


Bad data should lead to an error as close as possible to the source of the bad 
data, and do the wrong thing for a while before blowing up in some unexpected 
part of the code. Code defensively: if you want to be sure name[0] is a single 
character, make sure the test will only pass when given a single character.


-- 
Steven



More information about the Tutor mailing list