if/elif chain with assignment expressions

Paul Rubin http
Sun Jul 11 20:21:58 CEST 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:
   elif (y := g(x)) < 7:
   elif (y := h(x)) < 9:

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