[Tutor] Help me Be Pythonic [logic and readability]
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Tue, 28 May 2002 23:19:35 -0700 (PDT)
On Tue, 28 May 2002, Sean 'Shaleh' Perry wrote:
> > The reason for this is because find() will return -1 if it can't find
> > the string we're looking for. For example, if we play around with
> > find() in the interactive interpreter:
> >
>
> so why not do:
>
>
> if find() != -1?
Hi Sean,
This also works well. Since find() returns either '-1' if it can't find
the target string, or something else (the position) if it does find
something, we can compose the logic in several ways that'll work.
I feel that the important part is to be consistant; it would probably not
be a good thing to do it one way, and then switch over to the other, at
least, not without good reasons. What I mean is that something like:
###
for url in fileinput.input():
if url.find('.com') >= 0: print "success"
else: print "unavailable"
if url.find('.org') != -1: print "success"
else: print "unavailable"
###
would look a little off to me. Even though the logic is impeccable, the
different process toward getting at it is somewhat jarring, at least to my
eyes.
Even "worse" from a (subjective) consistancy standpoint might be:
###
for url in fileinput.input():
if url.find('.com') >= 0: print "success"
else: print "unavailable"
if url.find('.org') == -1: print "unavailable"
else: print "success"
###
... Although it does have a certain... symmetry to it... still, I don't
like it! It just feels like it... "bounces" to me, in a way that it
doesn't need to. At least in Python, I like code to flow quietly. These
are purely subjective, irrational terms, but that's just how it feels to
me. *grin*
Talk to you later!