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

Peter Otten __peter__ at web.de
Sat Feb 3 10:48:58 EST 2007


Jussi Salmela wrote:

> It's naturally clear that a combination of if-elifs-else is more
> adaptable to different situations, but the OP's question was:
> 
> I would like to do the equivalent if python of the C line:
> printf("I saw %d car%s\n", n, n != 1 ? "s" : "")

And my answer, triggered by your intermission

> And I'm starting to wonder what the 'obvious way' (as in 'Zen of Python')
> to write this would be.

was that in Python you would achieve the best results with if ... else
instead:

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

> In this question I thought I recognized the familiar
> tool=hammer==>problem:nail pattern of thought and tried to show
> that in addition to the ternary operator Python has other ways of
> resolving that particular problem of his.

It seems we operated on different levels of abstraction,

You: hammer=ternary operator
Me: hammer=oneliner
 
> I'm certainly not an advocate of one-liners because at their extreme
> they easily result in write-only solutions.

D'accord. Did I mention that, as a "for fun" approach, "s" * (n != 1) is
quite clever :-)

Peter



More information about the Python-list mailing list