468,168 Members | 1,456 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,168 developers. It's quick & easy.

Python equivalent to a C trick

Dan
Is there a python equivalent of this trick in C?

Logic_Test ? True_Result : False_Result

Example:
printf( "you have %i %s", num_eggs, num_eggs > 1 ? "eggs" : "egg" );
Jul 18 '05 #1
15 1481
On 9 Aug 2004 23:55:08 -0700, Dan <da**********@gmail.com> wrote:
Is there a python equivalent of this trick in C?

Logic_Test ? True_Result : False_Result

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

But I don't know if int(False)==0 and int(True)==1 are actually
guaranteed. And I wouldn't use it since it's ugly (IMHO).

You don't get the "only evaluate one" goodness of ?:

--
Sam Holden
Jul 18 '05 #2
Dan wrote:
Is there a python equivalent of this trick in C?

Logic_Test ? True_Result : False_Result
Logic_Test and True_Result or False_Result
would be a Python counterpart.
Example:
printf( "you have %i %s", num_eggs, num_eggs > 1 ? "eggs" : "egg" );


So the exmaple is converted to:
print "you have %d %s"%(num_eggs, (num_eggs > 1) and "eggs" or "egg")

But be warned that if True_Result is evaluated as False(e.g. True_Result
is an empty string), this doesn't work.

If you don't know what object is considered False in Python, check the
following document.

* 2.3.1 Truth Value Testing
http://docs.python.org/lib/truth.html

--
George
Jul 18 '05 #3
Dan wrote:
Is there a python equivalent of this trick in C?

Logic_Test ? True_Result : False_Result


The long answer to your question is at
http://www.python.org/peps/pep-0308.html

(in addition to the "hack" Sam posted :-)

Roger
Jul 18 '05 #4
Dan wrote:
Is there a python equivalent of this trick in C?

Logic_Test ? True_Result : False_Result

Example:
printf( "you have %i %s", num_eggs, num_eggs > 1 ? "eggs" : "egg" );


Logic_Test and True_Result or False_Result

Example:
print (num_eggs > 1) and 'eggs" or "egg"

Thomas
Jul 18 '05 #5
Thomas Krüger wrote:
Logic_Test and True_Result or False_Result

Example:
print (num_eggs > 1) and 'eggs" or "egg"


Be very careful that the "True_Result" in your formulation actually is
itself a Python true value, or this won't work:

print 'egg' + (numEggs == 1 and '' or 's')

will not work as expected.

--
__ Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
\__/ Melancholy men, of all others, are the most witty.
-- Aristotle
Jul 18 '05 #6
Sam Holden wrote:
But I don't know if int(False)==0 and int(True)==1 are actually
guaranteed. And I wouldn't use it since it's ugly (IMHO).


From the language ref at http://docs.python.org/ref/types.html#l2h-37

Booleans
These represent the truth values False and True. The two objects
representing the values False and True are the only Boolean objects.
The Boolean type is a subtype of plain integers, and Boolean values
behave like the values 0 and 1, respectively, in almost all contexts,
the exception being that when converted to a string, the strings
"False" or "True" are returned, respectively.

So yes, it's fully guaranteed.
Jul 18 '05 #7
"Sam Holden" <sh*****@flexal.cs.usyd.edu.au> wrote in message
news:slrnchgsml.8e4.sh*****@flexal.cs.usyd.edu.au. ..
On 9 Aug 2004 23:55:08 -0700, Dan <da**********@gmail.com> wrote:
Is there a python equivalent of this trick in C?

Logic_Test ? True_Result : False_Result

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

-- Paul
Jul 18 '05 #8
>>>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
Jul 18 '05 #9
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.
Jul 18 '05 #10
"Josef Meile" <jm****@hotmail.com> wrote in message
news:41********@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
Jul 18 '05 #11
Erik Max Francis <ma*@alcyone.com> wrote in message news:<41***************@alcyone.com>...
Thomas Krüger wrote:
Logic_Test and True_Result or False_Result

Example:
print (num_eggs > 1) and 'eggs" or "egg"


Be very careful that the "True_Result" in your formulation actually is
itself a Python true value, or this won't work:

print 'egg' + (numEggs == 1 and '' or 's')

will not work as expected.


For which reason the form (test and [true_result] or
[false_result])[0] is sometimes advocated. This starts to look a
little too cluttered for my liking, so I tend to use it only when the
'true_result' is a variable and might be instantiated to a negative
value.
Jul 18 '05 #12
Paul McGuire wrote:
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. So, I guess it is like the "foo" keyword.
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) Good point ;-)
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.

I like your solution and I think it even considers when n=0, while the
other example fails and write "You have 0 egg"
Jul 18 '05 #13
On Tue, 10 Aug 2004 23:23:07 GMT,
"Paul McGuire" <pt***@austin.rr._bogus_.com> wrote:
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)


Don't forget this one: You have -1 egg.

Regards,
Dan

--
Dan Sommers
<http://www.tombstonezero.net/dan/>
Never play leapfrog with a unicorn.
Jul 18 '05 #14
Dan wrote:
Is there a python equivalent of this trick in C?

Logic_Test ? True_Result : False_Result


There's something close:

Logic_Test and True_Result or False_Result

print 'you have %i egg%s' % (num_eggs, (num_eggs != 1) and 's' or '')

The main problem with this is that False_Result will get executed if
Logic_Test is false *or* True_Result evaluates to false. Witness the
following broken variation of the above:

print 'you have %i egg%s' % (num_eggs, (num_eggs == 1) and '' or 's')

So it's not perfect, but it is workable. And as a previous post
indicated, this situation is not likely to change. :)

-- Mark
Jul 18 '05 #15
Dan wrote:
Is there a python equivalent of this trick in C?

Logic_Test ? True_Result : False_Result

Example:
printf( "you have %i %s", num_eggs, num_eggs > 1 ? "eggs" : "egg" );

def numerus(n, sg, pl=None): .... if n == 1:
.... return article(sg)
.... elif n == 0:
.... return "no " + plural(sg, pl)
.... else:
.... return "%d %s" % (n, plural(sg, pl))
.... def article(sg): .... if sg[:1].lower() in "aeiou": # uniforms are off-limit
.... return "an " + sg
.... else:
.... return "a " + sg
.... def plural(sg, pl): .... if pl is None:
.... return sg + "s"
.... else:
.... return pl
.... numerus(1, "egg") 'an egg' numerus(2, "egg") '2 eggs' numerus(0, "egg") 'no eggs' numerus(1, "solution") 'a solution'


:-)

Refine as needed.

Peter

PS: The trick is to not use a trick.

Jul 18 '05 #16

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

12 posts views Thread by Raymond Hettinger | last post: by
68 posts views Thread by Lad | last post: by
134 posts views Thread by Joseph Garvin | last post: by
8 posts views Thread by Jan Danielsson | last post: by
2 posts views Thread by ajikoe | last post: by
267 posts views Thread by Xah Lee | last post: by
14 posts views Thread by mistral | last post: by
1 post views Thread by gcdp | last post: by
reply views Thread by gcreed | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.