if/elif chain with assignment expressions

Paul Rubin http
Sun Jul 11 14:21:58 EDT 2004


Sometimes you want to compute an expression, then do something with
the value if it meets a certain criterion; otherwise, try a different
expression (and maybe different criterion) instead, etc.  With := as
an assignment expression operator, you could write:

   if (y := f(x)) < 5:
       fred(y)
   elif (y := g(x)) < 7:
       ted(y)
   elif (y := h(x)) < 9:
       ned(y)
   etc.

Of course there are alternative ways of doing the same thing, but they
all seem to be messier.



More information about the Python-list mailing list