Comparison Style
Chris Angelico
rosuav at gmail.com
Thu Apr 25 01:57:49 EDT 2013
On Thu, Apr 25, 2013 at 3:49 PM, llanitedave <llanitedave at veawb.coop> wrote:
> Given that
>
> s = some static value
> i = a value incremented during a loop
>
> I'm used to comparing them as
>
> if i == s:
> # some code
>
> But for some unknown reason I did a switch
>
> if s == i:
> # same code
>
> It didn't seem to make any difference at first glance, so I just got to wondering --
It won't make any difference in any sort of sane code. If there's any
situation in which == is not reflexive, something seriously nasty is
going on.
> Is there a standard for comparison order? Is there any kind of performance difference? Is there even a tradition for one or the other? Are there any gotchas?
It's conventional to compare variables to constants, not constants to
variables (even in C where there's the possibility of mucking up the
operator, most people still compare variables to constants). I'd
normally use "i == s" there, treating s as a constant for the purpose
of the loop. Unless you're deliberately being poetical, language such
as "Three is the number thou shalt count" is distinctly abnormal, so
saying "if (5 == i)" is equally awkward. It's nothing major; mostly
it's like the algebraic convention of putting the more-known elements
earlier in a term (eg 2πix - 2 is known, 3.14159.... is mostly known,
i is imaginary but at least it's constant, and x is unknown).
> Do I need to get a hobby?
I thought programming WAS a hobby?
ChrisA
More information about the Python-list
mailing list