Python is known for its simple syntax. However, when you’re learning Python for the first time or when you’ve come to Python with a solid background in another programming language, you may run into some things that Python doesn’t allow. If you’ve ever received a Show
By the end of this tutorial, you’ll be able to:
Invalid Syntax in PythonWhen you run your Python code, the interpreter will first parse it to convert it into Python byte code, which it will then execute. The interpreter will find any invalid syntax in Python during this first stage of program execution, also known as the parsing stage. If the interpreter can’t parse your Python code successfully, then this means that you used invalid syntax somewhere in your code. The interpreter will attempt to show you where that error occurred. When you’re learning Python for the first time, it can be frustrating to get a You can’t handle invalid syntax in Python like other exceptions. Even if you tried to wrap a SyntaxError Exception and TracebackWhen the interpreter encounters invalid syntax in Python code, it will raise a You can see the invalid syntax in the dictionary literal on line 4. The second entry, Note that the traceback message locates the error in line 5, not line 4. The Python interpreter is attempting to point out where the invalid syntax is. However, it can only really point to where it first noticed a problem. When you get a In the example above, there isn’t a problem with leaving out a comma, depending on what comes after it. For example, there’s no problem with a missing comma after `SyntaxError`0 in line 5. But once the interpreter encounters something that doesn’t make sense, it can only point you to the first thing it found that it couldn’t understand. There are a few elements of a
In the example above, the file name given was There are two other exceptions that you might see Python raise. These are equivalent to
These exceptions both inherit from the Common Syntax ProblemsWhen you encounter a Misusing the Assignment Operator (`SyntaxError`5)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 code block below, you can see a few examples that attempt to do this and the resulting The first example tries to assign the value The second and third examples try to assign a string and an integer to literals. The same rule is true for other literal values. Once again, the traceback messages indicate that the problem occurs when you attempt to assign a value to a literal. It’s likely that your intent isn’t to assign a value to a literal or a function call. For instance, this can occur if you accidentally leave off the extra equals sign (`SyntaxError`5), which would turn the assignment into a comparison. A comparison, as you can see below, would be valid: Most of the time, when Python tells you that you’re making an assignment to something that can’t be assigned to, you first might want to check to make sure that the statement shouldn’t be a Boolean expression instead. You may also run into this issue when you’re trying to assign a value to a Python keyword, which you’ll cover in the next section. Misspelling, Missing, or Misusing Python KeywordsPython keywords are a set of protected words that have special meaning in Python. These are words you can’t use as identifiers, variables, or function names in your code. They’re a part of the language and can only be used in the context that Python allows. There are three common ways that you can mistakenly use keywords:
If you misspell a keyword in your Python code, then you’ll get a The message reads `try`3, but that’s not very helpful. The traceback points to the first place where Python could detect that something was wrong. To fix this sort of error, make sure that all of your Python keywords are spelled correctly. Another common issue with keywords is when you miss them altogether: Once again, the exception message isn’t that helpful, but the traceback does attempt to point you in the right direction. If you move back from the caret, then you can see that the `try`4 keyword is missing from the `try`2 loop syntax. You can also misuse a protected Python keyword. Remember, keywords are only allowed to be used in specific situations. If you use them incorrectly, then you’ll have invalid syntax in your Python code. A common example of this is the use of outside of a loop. This can easily happen during development when you’re implementing things and happen to move logic outside of a loop: Here, Python does a great job of telling you exactly what’s wrong. The messages `try`8 and `try`9 help you figure out exactly what to do. If this code were in a file, then Python would also have the caret pointing right to the misused keyword. Another example is if you attempt to assign a Python keyword to a variable or use a keyword to define a function: When you attempt to assign a value to It might be a little harder to solve this type of invalid syntax in Python code because the code looks fine from the outside. If your code looks good, but you’re still getting a The list of protected keywords has changed with each new version of Python. For example, in Python 3.6 you could use Another example of this is `except`8, which differs in Python 2 vs Python 3: Version`except`8 Type Takes A Value keyword no built-in function yes `except`8 is a keyword in Python 2, so you can’t assign a value to it. In Python 3, however, it’s a built-in function that can be assigned values. You can run the following code to see the list of keywords in whatever version of Python you’re running: `SyntaxError`1 also provides the useful `SyntaxError`2. If you just need a quick way to check the `except`0 variable, then you can use the following one-liner: This code will tell you quickly if the identifier that you’re trying to use is a keyword or not. Missing Parentheses, Brackets, and QuotesOften, the cause of invalid syntax in Python code is a missed or mismatched closing parenthesis, bracket, or quote. These can be hard to spot in very long lines of nested parentheses or longer multi-line blocks. You can spot mismatched or missing quotes with the help of Python’s tracebacks: Here, the traceback points to the invalid code where there’s a `SyntaxError`4 after a closing single quote. To fix this, you can make one of two changes:
Another common mistake is to forget to close string. With both double-quoted and single-quoted strings, the situation and traceback are the same: This time, the caret in the traceback points right to the problem code. The Quotes missing from statements inside an f-string can also lead to invalid syntax in Python: Here, the reference to the `SyntaxError`0 dictionary inside the printed f-string is missing the closing double quote from the key reference. The resulting traceback is as follows: Python identifies the problem and tells you that it exists inside the f-string. The message `SyntaxError`1 also indicates what the problem is. The caret in this case only points to the beginning of the f-string. 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. There’s an unterminated string somewhere inside that f-string. You just have to find out where. To fix this problem, make sure that all internal f-string quotes and brackets are present. 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: When you run this code, you’ll be told that there’s a problem with the call to `SyntaxError`2: What’s happening here is that Python thinks the list contains three elements: `SyntaxError`3, `SyntaxError`4, and `SyntaxError`5. Python uses whitespace to group things logically, and because there’s no comma or bracket separating `SyntaxError`6 from `SyntaxError`7, Python lumps them together as the third element of the list. Another variation is to add a trailing comma after the last element in the list while still leaving off the closing square bracket: Now you get a different traceback: In the previous example, `SyntaxError`6 and `SyntaxError`7 were lumped together as one element, but here you see a comma separating the two. Now, the call to `SyntaxError`7 gets added as the fourth element of the list, and Python reaches the end of the file without the closing bracket. The traceback tells you that Python got to the end of the file (EOF), but it was expecting something else. In this example, Python was expecting a closing bracket (`SyntaxError`1), but the repeated line and caret are not very helpful. Missing parentheses and brackets are tough for Python to identify. Sometimes the only thing you can do is start from the caret and move backward until you can identify what’s missing or wrong. Mistaking Dictionary SyntaxYou saw that you could get a Once again, this error message is not very helpful. The repeated line and caret, however, are very helpful! They’re pointing right to the problem character. This type of issue is common if you confuse Python syntax with that of other programming languages. You’ll also see this if you confuse the act of defining a dictionary with a `SyntaxError`4 call. To fix this, you could replace the equals sign with a colon. You can also switch to using `SyntaxError`4: You can use `SyntaxError`4 to define the dictionary if that syntax is more helpful. Using the Wrong IndentationThere are two sub-classes of
While other programming languages use curly braces to denote blocks of code, Python uses whitespace. That means that Python expects the whitespace in your code to behave predictably. It will raise an `SyntaxError`8 if there’s a line in a code block that has the wrong number of spaces: This might be tough to see, but line 5 is only indented 2 spaces. It should be in line with the `try`2 loop statement, which is 4 spaces over. Thankfully, Python can spot this easily and will quickly tell you what the issue is. There’s also a bit of ambiguity here, though. Is the `'jim'`2 line intended to be after the `try`2 loop or inside the `try`2 loop block? When you run the above code, you’ll see the following error: Even though the traceback looks a lot like the The other type of If your tab size is the same width as the number of spaces in each indentation level, then it might look like all the lines are at the same level. However, if one line is indented using spaces and the other is indented with tabs, then Python will point this out as a problem: Here, line 5 is indented with a tab instead of 4 spaces. This code block could look perfectly fine to you, or it could look completely wrong, depending on your system settings. Python, however, will notice the issue immediately. But before you run the code to see what Python will tell you is wrong, it might be helpful for you to see an example of what the code looks like under different tab width settings: Notice the difference in display between the three examples above. Most of the code uses 4 spaces for each indentation level, but line 5 uses a single tab in all three examples. The width of the tab changes, based on the tab width setting:
When you run the code, you’ll get the following error and traceback: Notice the The solution to this is to make all lines in the same Python code file use either tabs or spaces, but not both. For the code blocks above, the fix would be to remove the tab and replace it with 4 spaces, which will print `SyntaxError`2 after the `try`2 loop has finished. Defining and Calling FunctionsYou might run into invalid syntax in Python when you’re defining or calling functions. For example, you’ll see a The traceback here is very helpful, with the caret pointing right to the problem character. You can clear up this invalid syntax in Python by switching out the semicolon for a colon. In addition, keyword arguments in both function definitions and function calls need to be in the right order. Keyword arguments always come after positional arguments. Failure to use this ordering will lead to a Here, once again, the error message is very helpful in telling you exactly what is wrong with the line. Changing Python VersionsSometimes, code that works perfectly fine in one version of Python breaks in a newer version. This is due to official changes in language syntax. The most well-known example of this is the `except`8 statement, which went from a keyword in Python 2 to a built-in function in Python 3: This is one of the examples where the error message provided with the Another problem you might encounter is when you’re reading or learning about syntax that’s valid syntax in a newer version of Python, but isn’t valid in the version you’re writing in. An example of this is the f-string syntax, which doesn’t exist in Python versions before 3.6: In versions of Python before 3.6, the interpreter doesn’t know anything about the f-string syntax and will just provide a generic `except`3 message. The problem, in this case, is that the code looks perfectly fine, but it was run with an older version of Python. When in doubt, double-check which version of Python you’re running! Python syntax is continuing to evolve, and there are some cool new features introduced in Python 3.8: If you want to try out some of these new features, then you need to make sure you’re working in a Python 3.8 environment. Otherwise, you’ll get a Python 3.8 also provides the new `SyntaxError`08. You’ll see this warning in situations where the syntax is valid but still looks suspicious. An example of this would be if you were missing a comma between two tuples in a list. This would be valid syntax in Python versions before 3.8, but the code would raise a `SyntaxError`09 because a tuple is not callable: This `SyntaxError`09 means that you can’t call a tuple like a function, which is what the Python interpreter thinks you’re doing. In Python 3.8, this code still raises the `SyntaxError`09, but now you’ll also see a `SyntaxError`08 that indicates how you can go about fixing the problem: The helpful message accompanying the new `SyntaxError`08 even provides a hint (`SyntaxError`14) to point you in the right direction! ConclusionIn this tutorial, you’ve seen what information the When you’re writing code, try to use an IDE that understands Python syntax and provides feedback. If you put many of the invalid Python code examples from this tutorial into a good IDE, then they should highlight the problem lines before you even get to execute your code. Getting a |