Stephen Nelson-Smith wrote:
A friend of mine mentioned what he called the 'pythonic' idiom of:

print a or b

Isn't this a 'clever' kind or ternary - an if / else kind of thing?

I would say it's perfectly idiomatic in Python, but
not as a ternary. If you want a ternary use the
(relatively) recently-introduced:

a if <cond> else b

eg:

things = [1, 2 ,3]
print "%d thing%s found" % (len (things), "" if len (things) == 1 else "s")

Before this operator came along, people used to use
more-or-less clever-clever tricks with boolean operators
or using the fact that bool / int are interchangeable:

['s', ''][len (things) == 1]

The "a or b" idiom is most commonly used for default-type
situations:

def f (a, b=None):
 print "a", b or "<Unknown>"


I don't warm to it... should I?

Up to you :) But I regard it as a useful idiom.

TJG
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to