Toggle

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Oct 8 21:29:08 EDT 2014


Seymore4Head wrote:

> I want to toggle between color="Red" and color="Blue"
> Here is one:
>     if color == "Red":
>         color = "Blue"
>     else:
>         color = "Red"

Apart from the horrible spelling of colour :-) that seems fine to me. You
might wish to include a comment:

# Assumes that color can only take the values "Red" or "Blue".

just before the toggle code. But even better than a comment is an assertion:

assert color in ("Red", "Blue")
if color == "Red":
    color = "Blue"
else:
    color = "Red"

This makes it a "checked comment" -- the primary purpose of the assert here
is as a comment, but the interpreter will by default actually check that it
is true (although that can be turned off by the user).

You can find out more about good, and bad, uses of assert here:

http://import-that.dreamwidth.org/676.html


> Here is two:
> if x = "True" color = "Red"
> else:
> color="Blue"
> x= not x

That gives SyntaxError. And it's wrong because you are confusing the
*string* "T r u e" with the constant True. It should be:

assert isinstance(x, bool)
if x:  # don't write "if x == True" since that is redundant
    color = 'Red'
else:
    color = 'Blue'
x = not x

 
> Others?

color = ("Red", "Blue")[color == "Red"]

color = {"Red": "Blue", "Blue": "Red"}[color]

color = "Red" if color == "Blue" else "Blue"


There may be even more complicated, obscure or obfuscated versions possible.


-- 
Steven




More information about the Python-list mailing list