Python equivalent to a C trick

Josef Meile jmeile at hotmail.com
Tue Aug 10 16:46:57 EDT 2004


>>>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



More information about the Python-list mailing list