Misusing the Assignment Operator
Misusing the Assignment Operator (
There are several cases in Python where you’re not able to make assignments to objects. Some examples are assigning to literals and function calls. In the following code, you’re going to see a few examples that attempt to do this, and the resulting
00:19 So, throughout this course, all of the Python examples that you see in a REPL will be done in bpython, rather than the standard Python REPL. It’s functionally identical, but it provides some nice code highlighting by using color.
So, here we’re going to try and assign
5 to the length of
Now as you can see, that has generated a
SyntaxError saying it can’t assign to a function call.
Here’s another example:
can't assign to literal.
And again, when we try the reverse, we also get
can't assign to literal. The second and third examples here both tried to do the same thing: assigning a string or an integer to literals.
01:05 The same rule is true for other literal values. Once again, the traceback messages here indicate that the problem occurs when you attempt to assign a value to a literal.
01:15 One thing to note here is that these examples in the REPL are missing the repeated code line and caret pointing to the problem in the traceback. The exceptions and trackbacks you see in a REPL are different to when you execute the code from a file.
01:29 If this code was in a file, you’d get the repeated code line and caret pointing to the problem, as you saw previously. So, this kind of misuse of the assignment operator is the kind of thing, certainly, I can say I do more than I should admit to.
01:42 It’s often been done because I’ve forgotten the extra equal sign when I’m trying to actually perform a comparison. So, seeing the first example corrected
does what I actually wanted, which was to check that the length of
'hello' was equal to
5, and you can see it returns the value
02:01 Most of the time, when Python tells you you’re making an assignment to something that can’t be assigned to, this is the thing to check first: that, in fact, you should be making a comparison.
02:11 You may also run into this issue when you’re trying to assign a value to a Python keyword, which is going to be covered in the next section.
Become a Member to join the conversation.