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

Jussi Salmela tiedon_jano at hotmail.com
Sat Feb 3 10:27:06 EST 2007


Peter Otten kirjoitti:
> Isn't that obvious? Don't do it in one line:
> 
> if n == 1:
>     print "I saw a car"
> else:
>     print "I saw %d cars" % n
> 
> I guess that most of us will have read, understood, and verified (are there
> any errors or cases that should be covered but aren't) those four lines
> faster than any of the "smart" constructs, including the official 2.5
> ternary operator. Now modify all proposed versions to print
> 
> I didn't see any cars
> I saw 7 cars missing
> 
> for n=0 and n=-7, respectively, and you will see 1 light :-)
> 
> Peter
> 

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" : "")

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.

I'm certainly not an advocate of one-liners because at their extreme
they easily result in write-only solutions.

Cheers,
Jussi



More information about the Python-list mailing list