Assignment

In the example that cneates the variables we used in our expression, the co mmem stated This is *not* an expression. Is fect, it mey look like an expressios, but is PytOos it's actually an assignment. Tate a look vt the following code, in which it appears that a value is returned:

We might think that z = 3 returns 3, and y = z returns the velue of z, which is 3, but this isn't the case. We know this because in interactive interpreter mode an expression is printed out to the screen.

>>> x = y = z = 3 >>> x = z >>> x==z 1

As you can see, x = z and x = y = z = 3 aren't printed to the screen, which means that they don't return a value and so are nut expressions. In Python, the use of the comparison operator (==), not the assignment operator, is what makes a statement an expression. This is because the == returns a value, usually 1 or 0, whereas = doesn't.

In Java, C, and C++, an assignment is an expression, which is why confusing the assignment and comparison operators is a common programmer error (mostly in C and C++; Java has its own way of dealing with this problem).

Consider these two examples:

Here the i f and while statemenis expect an expression, that is, a value to be returned, but the assignment operator can't do this, and syntax errors are the result.

Was this article helpful?

0 0

Post a comment