else on the same line - howto

Caleb Land bokonon at rochester.rr.com
Wed Oct 15 12:47:36 EDT 2003


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)

-Caleb




More information about the Python-list mailing list