Python equivalent to a C trick

Josef Meile jmeile at hotmail.com
Tue Aug 10 16:50:27 EDT 2004


Josef Meile wrote:
>>>> 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 !=).
Correction: The error happens only when using the ">" operator. With the 
"!=" doesn't happen.



More information about the Python-list mailing list