Can I use a conditional in a variable declaration?

Kent Johnson kent at kentsjohnson.com
Sat Mar 18 23:15:25 EST 2006


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")

If the value for the 'true' case can never have a boolean value of 
False, you can use this form:

a = (a == "yes") and "go ahead" or "stop"

The short-circuit evaluation of 'and' and 'or' give the correct result. 
This will not work correctly because the 'and' will always evaluate to 
"" which is False so the last term will be evaluated and returned:

a = (a == "yes") and "" or "stop"

and IMO the extra syntax needed to fix it isn't worth the trouble; just 
spell out the if / else.

Kent



More information about the Python-list mailing list