Can I use a conditional in a variable declaration?

Georg Brandl g.brandl-nospam at gmx.net
Sun Mar 19 05:38:29 EST 2006


Jeffrey Schwab wrote:
> volcs0 at gmail.com wrote:
> 
>> I want the equivalent of this:
>> 
>> if a == "yes":
>>    answer = "go ahead"
>> else:
>>    answer = "stop"
>> 
>> in this more compact form:
>> 
>> a = (if a == "yes": "go ahead": "stop")
>> 
>> is there such a form in Python? I tried playing around with lambda
>> expressions, but I couldn't quite get it to work right.
> 
> Rather than lambda, this merits a named function.  You only have to 
> define it once.
> 
> def mux(s, t, f):
>      if s:
>          return t
>      return f

But be aware that this is not a complete replacement for a syntactic
construct. With that function, Python will always evaluate all three
arguments, in contrast to the and/or-form or the Python 2.5 conditional.

You can show this with

test = mux(False, 1/0, 1)

and

test = False and 1/0 or 1

Georg



More information about the Python-list mailing list