"if {negative}" vs. "if {positive}" style (was: New to Python)

Tim Chase python.list at tim.thechases.com
Tue Feb 9 22:36:50 EST 2010


Larry Hudson wrote:
> But a minor rearrangement is simpler, and IMHO clearer:
> 
> if 'mystring' not in s:
>      print 'not found'
> else:
>      print 'foundit'
>      print 'processing'

I've always vacillated on whether that would better be written as 
Larry does, or as

   if 'mystring' in s
     print 'foundit'
     print 'processing'
   else:
     print 'not found'

removing the "not" from the condition.  I admit I choose one over 
the other based on some gut-feeling aesthetic that I can't really 
nail down.  I think one of my major influencing factors revolves 
around the negative "not" portion having one or two lines and the 
  positive portion having a large block of code.  If the 
code-blocks are more equal in size, I tend to use "if 
{positive}", but if the negative "not" section is only 1-2 lines, 
I tend to do as Larry writes and make it harder to miss by using 
"if {negative}".  Otherwise the "if {positive}...else" can end up 
sufficiently distant from the "if" that it's easy to miss.

Any thoughts on how others make the choice?

-tkc





More information about the Python-list mailing list