Joe Green said:
Sorry, I cant help aking stupid questions:
I understand why we need = = in C, but why in Python (or Java),
surely if you write
if a=b: pass # syntax error
it could not possibly mean anything other than what I intended
(which was of course if a = = b
?
Well, it could mean "if the value of a is True, after being assigned the
value of b" (which is what it would mean in C/C++, Java, and several other
languages). So, I suppose "==" is used to distinguish between assignment(or
binding) and tests for equality. I suppose the question you could ask
yourself as a language designer is "Is it preferrable to require different
notation for these different operations, or to use the same notation and
have its semantics differ depending upon the context in which it appears?".
In Python, they've chosen the former. I think there are languages that use
the latter, but none come to mind at the moment. Since Python does not allow
assignment in expressions, it's seems reasonable that your suggestion could
be introduced, but I hazard to guess that it would introduce more confusion
than clarity. For instance, people familiar with C/C++, Java, etc. (and even
many who are not familiar with those languages) will have very different
expectations of what "if a = b:" should mean. In fact, there are frequent
requests on this newsgroup for that expression to take on the meaning it has
in those other languages, rather than result in an exception, as it does in
this one (see
http://www.python.org/doc/faq/general.html#why-can-t-i-use-an-assignment-in-an-expression).
In an alternate version of the faq (located here:
http://python.is.co.za/doc/faq/general.html#why-can-t-i-use-an-assignment-in-an-expression),
there is mention of introducing ":=" for assignment. If you had that, then
you could use "=" as a test for equality with a bit less confusion. Of
course, everyone would have to go back through their old code and change
their "a=b"s to "a:=b", and all of their "a==b"s to "a=b". Hmm. And I
suppose you might want to change "+=", "-=", etc. to "+:=", "-:=", etc. for
symmetry ... on second thought ... maybe not. Anyway, after all of that, the
answer to your question "Why do we need == in Python?" is "We don't, really,
but that's what Guido wanted/chose". At least, I don't believe we _need_
it - I think it would be possible to design the language to interpret "a=b"
as a test for equality, when found in an expression, and as assignment, when
it is not. But they haven't done that in Python, and it doesn't seem likely
that it will be done. I don't have a problem with that. I like the way it's
done now. But, of course, tastes will vary.
Was that at all helpful?
Sean