Missing Parentheses, Brackets, and Quotes
Here, the traceback points to the invalid code, where there’s a
t and a single quote after a previous closing single quote. To fix this, you can make one of two changes. Firstly, you can escape the single quote with a backslash as seen in the example here.
00:53 We can already see that bpython is highlighting this code appropriately, so it looks like it’s going to be okay. Python is happy with it as well. A second option is to surround the entire string in double-quotes instead, as seen in the example below. Let’s see that in action.
01:17 Once more, you can see that bpython is highlighting this appropriately for a string, so it appears to be happy with what we’ve done. So is Python. Another common mistake is to forget to close a string. With both double-quoted and single-quoted strings the situation and traceback will be the same.
This time, the caret in the traceback points right to the problem code. The
EOL while scanning string literal is a little more specific and helpful in determining the problem.
01:57 This means that the Python interpreter got to the end of the line, EOL, before an open string was closed. To fix this, close the string with a quote that matches the one you used to start it. In these cases, the first would be with a double quote, the second would be with a single quote.
Quotes missing from statements inside an f-string can also lead to invalid syntax in Python. Here, the reference to the
ages dictionary inside the printed f-string is missing the closing single quote from the key reference.
02:51 The caret in this case only points to the beginning of the f-string that has the problem. This might not be as helpful as when the caret points to the problem area of the f-string, but it does narrow down where you need to look.
03:14 The situation is mostly the same for missing parentheses and brackets. If you leave out the closing square bracket from a list, for example, then Python will spot that and point it out. There are a few variations of this, however. The first is to leave the closing bracket off of the list.
So here, you see the code with a problem at line 3. When you run it, you’re told that there’s a problem with the call to
print(). What’s happening here is that Python thinks the list contains three elements,
In the previous example,
print(foo) were lumped together as one element, but here there is a comma separating the two. Now, the call to
print(foo) gets added to the fourth element of the list, and Python reaches the end of the file without the closing bracket.
04:35 The traceback tells you that Python has got to the end of file, EOF, but it was expecting something else. In this example, Python was expecting a closing bracket, but the repeated line and caret are not very helpful. Missing parentheses and brackets are tough for Python to identify.
Become a Member to join the conversation.