else on the same line - howto
Helmut Jarausch
jarausch at remove.igpm.rwth-aachen.de
Thu Oct 16 03:34:20 EDT 2003
Caleb Land wrote:
> Helmut Jarausch <jarausch at remove.igpm.rwth-aachen.de> wrote in message news:<bmj859$iph$1 at nets3.rz.RWTH-Aachen.DE>...
>
>>Sorry for this trivial question
>>
>>Since Python lacks conditional expression
>>
>>like
>>
>>k+= (dy >= 0 ? 1 : -1)
>>
>>I would like to write
>>if dy >= 0 : k+= 1; else: k-= 1
>>
>>instead of
>>if dy >= 0 : k+= 1
>>else : k-= 1
>>
>>but I don't know the exact syntax for writing
>>the 'else' clause onto the same line.
>
>
> If you really want such a thing you could make a generic function that
> would replace ?:
>
> def iif(cond, t, f):
> if cond:
> return t
> else:
> return f
>
> k += iif(dy >= 0, 1, -1)
Thanks to all who have replied. It's amazing how many different
solutions are possible in Python.
Among all such a solution by a function is most readable (to me)
and I can well imagine such a function a builtin.
I have been teaching course in C++ to beginners and made the experience
that well chosen conditional expression are not obscure.
One can misuse any feature of a language to write obscure code.
Especially for the expression of a 'return' statement a conditional
expression might be a good idea.
Helmut.
---
Helmut Jarausch
RWTH-Aachen University
Germany
More information about the Python-list
mailing list