Can I use a conditional in a variable declaration?

Jeffrey Schwab jeff at schwabcenter.com
Sun Mar 19 06:16:13 CET 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")
> 
> 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

def interpret(a):
     answer = mux(a == "yes", "go ahead", "stop")
     print answer

interpret("yes")    # Prints "go ahead."
interpret("no")     # Prints "stop."



More information about the Python-list mailing list