the death of lecter
Terry Reedy
tjreedy at udel.edu
Tue Sep 12 11:19:47 EDT 2000
"Michal Wallace" <sabren at manifestation.com> wrote in message
news:Pine.BSF.4.10.10009111130480.20577-100000 at chi.pair.com...
...
> * immediate if:
> print 'x is', x > 0 ? 'positive' : 'negative'
...
> # I still wish we had a ?: operator..
> # It would be great for lambdas!
But we pretty much do, already.
print 'x is', (x>0) and 'positive' or 'negative'
or, debugged,
>>> def pr(x):
... print 'x is', (x>0) and 'positive' or (x==0) and 'zero' or 'negative'
...
>>> pr(1)
x is positive
>>> pr(0)
x is zero
>>> pr(-1)
x is negative
The 'condition and then-expression or else-expression' construction only
fails if the then-expression evaluates as false. If the else-expression
evaluates as true, reverse the condition. If both are false (rare), then
use a tuple trick (in the FAQ?). For the above,
>>> def pr(x): print 'x is', ('negative','zero','positive')[cmp(x,0)+1]
...
>>> pr(1)
x is positive
>>> pr(0L)
x is zero
>>> pr(-1.0)
x is negative
Terry J. Reedy
More information about the Python-list
mailing list