Can I use a conditional in a variable declaration?

Sion Arrowsmith siona at
Tue Mar 21 16:59:56 CET 2006

Ron Adam  <rrr at> wrote:
>volcs0 at wrote:
>> I want the equivalent of this:
>> if a == "yes":
>>    answer = "go ahead"
>> else:
>>    answer = "stop"
>> in [a] more compact form:
>I sometimes find it useful to do:
>     answers = {True: "go ahead", False: "stop"}
>     answer = answers[a == "yes"]

In this particular case, you can get it even more compact as

answer = {"yes": "go ahead"}.get(a, "stop")

but that's sacrificing elegance and readability for bytes. When I find
myself with code like the OP's, I usually rewrite as:

answer = "stop"
if a == "yes":
    answer = "go ahead"

\S -- siona at --
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |    -- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump

More information about the Python-list mailing list