Search code examples
pythonpython-3.xvariable-assignmentassignment-operator

Can someone explain why this compiles?


I am a newbie in Python and was experimenting and just ran the following code:

a=13
a==14
print(a)

I expected the program not to compile due to the second line although surprisingly it does (although I couldn't see any changes that it made). Can someone explain why? If I use a===14 instead of a==14 there's an error.


Solution

  • a==14 is not a statement, it's an expression. It produces a boolean result, that is discarded as soon as it is produced. It is a line that has absolutely no effect on the program.

    On the other hand, there is no === operator in python, that's why your program fails in that case. Contrary to javascript, python is a strongly typed language, it does not do implicit conversions. The == of python is similar to === in javascript.