Can I use a conditional in a variable declaration?
Sion Arrowsmith
siona at chiark.greenend.org.uk
Tue Mar 21 10:59:56 EST 2006
Ron Adam <rrr at ronadam.com> wrote:
>volcs0 at gmail.com 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 chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "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