Python equivalent to a C trick
Peter Otten
__peter__ at web.de
Wed Aug 11 15:29:10 EDT 2004
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.
More information about the Python-list
mailing list