if/elif chain with assignment expressions

steve holden sholden at holdenweb.com
Sun Jul 11 17:31:20 EDT 2004


Paul Rubin wrote:
> 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.

Indeed, you  might think so. But this topic has been discussed 
exhaustively (which isn't to say you aren't about to hear a lot more 
about the subject) in this group, and the assignment operation is *not* 
an operator for specific reasons the FAQ attempts to make clear in 
http://www.python.org/doc/faq/general.html#why-can-t-i-use-an-assignment-in-an-expression

regards
  Steve




More information about the Python-list mailing list