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

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Fri Feb 2 12:59:45 EST 2007


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




More information about the Python-list mailing list