conditional expressions

Mike Rovner mike at bindkey.com
Fri Sep 27 18:24:04 EDT 2002


"Terry Reedy" <tjreedy at udel.edu> wrote in message
news:t_3l9.334924$AR1.14880141 at bin2.nnrp.aus1.giganews.com...
> na=1; np=3; nl=1; ng=0
> print "Found: %d apple%s, %d plum%s, %d lemon%s, and %d grape%s." %\
> (na, na!=1 and 's' or '', np, np!=1 and 's' or '', nl, nl!=1 and 's'
> or '', ng, ng!=1 and 's' or '')
>
> Found: 1 apple, 3 plums, 1 lemon, and 0 grapes.
>
> Alternatives to this 'risky' construct:
> 1. forgo the nicety of correct English output
> 2. nest if/else four levels deep to choose correct variant of 16 print
> statements (ugh)
> 3. precalculate 4 suffixes and store in 4 temp vars with 4 if/else's
> (8 or 16 lines);
>    though clearly superiour to 2), this is still tedious with some
> risk of typo error.
>
4. Try:
use_s=('','s')
print "Found: %d apple%s, %d plum%s, %d lemon%s, and %d grape%s." %\
(na, use_s[na!=1], np, use_s[np!=1], nl, use_s[nl!=1], ng, use_s[ng!=1])








More information about the Python-list mailing list