Can I use a conditional in a variable declaration?

Ron Adam rrr at ronadam.com
Sun Mar 19 03:18:02 EST 2006


volcs0 at gmail.com wrote:
> I've done this in Scheme, but I'm not sure I can in Python.
> 
> 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.


I sometimes find it useful to do:


     answers = {True: "go ahead", False: "stop"}

     answer = answers[a == "yes"]



This is also sometimes useful when you want to alternate between two values.

     values = {'a':'b', 'b':'a'}   # define outside loop

     while 1:
     	v = values[v]             # alternate between 'a' and 'b'
         ...

There are limits to this, both the keys and the values need to be hashable.


Cheers,
   Ron
















More information about the Python-list mailing list