Ternery operator
Uwe Schmitt
uwe.schmitt at procoders.net
Tue Sep 9 05:33:41 EDT 2003
Peter Hansen <peter at engcorp.com> wrote:
> Uwe Schmitt wrote:
>>
>> Andrew Chalk <achalk at xxxmagnacartasoftware.com> wrote:
>> > Is there a python equivalent of the C ternery operator?
>>
>> > I.e.:
>>
>> > fred = (x == 1) ? 12 : 15
>>
> I would think a *Python* equivalent to ?: should not use
> direct equality comparison with 1. Better to drop the "==1"
> parts in any of the above, to allow the usual Python interpretation
> of what is True and what is False to occur.
> ...so fred = [12, 15][not x] is sufficient.
You made a mistake, compare :
[12,15][not x] (x==1) ? 12 : 15
x=0 15 15
x=1 12 12
x=2 12 15
Normaly you should simulate "C ? T : F"
either by
[T,F][not C]
or
(C and [T] or [F])[0]
in the first case T and F are evaluated allways,
the latter solution does short circuit evaluation,
which is according to the C/C++ semantics of the
ternary operator.
Greetings, Uwe.
--
Dr. rer. nat. Uwe Schmitt http://www.procoders.net
schmitt at procoders.net "A service to open source is a service to mankind."
More information about the Python-list
mailing list