compound statement from C "<test>?<true-val>:<false-val>"

Carl Banks pavlovevidence at gmail.com
Sun Feb 11 19:57:07 EST 2007


On Feb 11, 5:16 pm, "Holger" <ish... at gmail.com> wrote:
> Thanks all for good input.
> It seems like there's no the-python-way for this one.
>
> Currently I'm forced to use cygwin - and python in cygwin is still not
> 2.5 so I can't use the new inline if-else ternary operator.
>
> > >> if n == 1:
> > >>     print "I saw a car"
> > >> else:
> > >>     print "I saw %d cars" % n
>
> Personally I don't like the if-else approach because of the don't-
> repeat-yourself philosophy

You shouldn't be worried a repeating few characters from a short,
simple print statement.  It's not a mortal sin.

You don't need any ternary operator to avoid repetition, anyways.  You
could factor the common parts out like this:

if n == 1:
    what = "a car"
else:
    what = "%d cars" % n
print "I saw %s" % what

but what's the point?  It's just a few repeated characters two lines
apart.  Peter's version is the most easily read version here,
including the one using the official ternary operator.


Carl Banks




More information about the Python-list mailing list