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

Peter Otten __peter__ at web.de
Sat Feb 3 09:07:02 EST 2007


Jussi Salmela wrote:

> bearophileHUGS at lycos.com kirjoitti:
>> Jussi Salmela:
>>> In this particular case you don't need the ternary operator:
>>> print "I saw %d car%s\n" % (n, ("", "s")[n != 1])
>> 
>> The last newline is probably unnecessary. This seems be a bit more
>> readable:
>> print "I saw", n, "car" + ("", "s")[n != 1]
>> 
>> With Python 2.5 this looks better:
>> print "I saw", n, "car" + ("" if n == 1 else "s")
>> 
>> Or the vesion I like better:
>> print "I saw", n, ("car" if n == 1 else "cars")
>> 
>> Those () aren't necessary, but they help improve readability, and
>> avoid problems with operator precedence too. That if has a quite low
>> precedence.
>> 
>> Bye,
>> bearophile
>> 
> This is getting weird but here's 2 more in the spirit of
> "who needs the ternary operator - I don't!". And I'm starting to
> wonder what the 'obvious way' (as in 'Zen of Python') to write
> this would be.
> 
> print "I saw %d car%s" % (n, {1:''}.get(n==1, 's'))
> 
> print "I saw %d car%s" % (n, 's'*(n!=1))

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




More information about the Python-list mailing list