For review: PEP 308 - If-then-else expression
gustav at morpheus.demon.co.uk
Sat Feb 8 21:19:56 CET 2003
Erik Max Francis <max at alcyone.com> writes:
> So you'd want conditional expressions in things like [example in C]:
> printf("I have %d %s%s.\n", count, noun, count == 1 ? "" : "s");
> Here's an example where I want to do an if...else but that is really a
> minor point the big picture. The if...else is necessary, but it isn't
> the main focus.
Actually, this is an interesting example. To look at the same problem
another way, you could write
def quantify(noun, count):
if count == 1:
return noun + "s"
print "I have %d %s" % (count, quantify(noun, count))
which, to my mind, is even more clear (especially if you put a little
more effort into naming the "quantify" function than I did).
It also has some other advantages:
* If you need to change the rules, you only have one place to
change. With this example, there's the obvious case of
internationalisation where you might need to do this.
* If and when you *do* change it, you don't hit problems if the
change doesn't conform to the pattern of simply changing or
adding a suffix.
If I as feeling pedantic, I could argue that not having a conditional
expression is *good* because it avoids you getting sucked into writing
code with maintenance issues like this... Of course, you can't make
people write good code - someone who misses conditional expressions is
more likely to just write something like
s = "s"
if count = 1: s = ""
print "I have %d %s%s" % (count, noun, s)
and complain that it would have been much simpler with a conditional
Or, to put it another way, not having conditional expressions makes
you think about how to overcome the lack. And anything that makes you
think about the best way to code something can't be all bad.
This signature intentionally left blank
More information about the Python-list