Python equivalent to a C trick

Paul McGuire ptmcg at austin.rr._bogus_.com
Tue Aug 10 19:23:07 EDT 2004


"Josef Meile" <jmeile at hotmail.com> wrote in message
news:4119327f$1 at pfaff2.ethz.ch...
> >>>Example:
> >>>printf( "you have %i %s", num_eggs, num_eggs > 1 ? "eggs" : "egg" );
> >>
> >>print "you have %i %s" % ( num_eggs, ("egg","eggs")[num_eggs>1] )
> >
> >
> > I would choose "!=" instead of ">" as the comparison operator.  I think
the
> > accepted vernacular is:
> >
> > you have -2 eggs
> > you have -1 eggs
> > you have 0 eggs
> > you have 1 egg
> > you have 2 eggs
> > you have 3 eggs
> > you have 0.5 eggs
> No offense intended, but the negative and float cases don't make any
> sense for me on this context. You can't have -2 eggs or 0.5 eggs. The
> last case won't occure as well because the output is being parsed to
> int, so, you will get "you have 0 egg", which is again false. This error
> happens with both solutions (with > and with !=).
>
> Regards,
> Josef
No offense taken! :)

The OP was looking for a general solution to <condition> ? <if-true-action>
: <else-action>, then gave us the "you have n egg(s)" example.

In the general case, the number for comparison isn't always an integer
quantity such as eggs.  It could be "dollar(s)"/"euro(s)"/"Swiss
franc(s)"/"yen" (hmm, I guess "yen" isn't a problem...), or "ton(s) of
salami", or "pound(s) of cement", or "degree(s) Celsius", or...  Anyway,
even though eggs are usually counted from 1 to n in integer steps, other
quantities can easily be negative and/or continuous.  Still the singular -
in English, anyway - is usually used *only* when the quantity is 1.
Fractional and zero amounts, even though less than 1, still most naturally
use the plural form.

You have 0.5 dollars
You have gained 1 pound
You increased temperature by 0 degrees
You have -2 dollars (that is, you owe 2 dollars)

My point (which I guess didn't come across too well) was that this is a
typical coding and testing error, in which only positive integer values > 0
are assumed, because we often mentally equate "plural" with "more than 1".
But whether you are working in an integer, real, positive-only, or all
numbers context, testing with n != 1 should determine whether singular noun
should be used.

-- Paul





More information about the Python-list mailing list