Python

Python Syntax Errors

Welcome to chapter 8 of our python tutorial. In the previous chapter, we learned about Python numbers and how to use them in expressions. Throughout this chapter, you'll look at frequent examples of incorrect Python syntax and learn how to fix them.

At the end of this tutorial, you will:

  • Distinguish incorrect syntax in Python
  • Get familiar with SyntaxError tracebacks
  • Fix improper syntax or avoid it altogether

In Python, what is an invalid syntax?

Before transforming your Python code to Python byte code, the interpreter parses it. The parsing stage is where the interpreter searches for any instances of improper syntax in the program. Using the wrong syntax in your Python code will lead the interpreter to be unable to decipher it. The interpreter will try to show you exactly where the issue occurred.

Learning Python and encountering a SyntaxError can be a frustrating experience. If you're having trouble figuring out where the grammatical errors are, Python can provide you with a traceback that can be helpful. It's not uncommon for the resulting code to be nothing short of spectacular.

Please keep in mind that even if your code is syntactically valid, you may encounter other issues.

In Python, unlike other exceptions, improper syntax cannot be tolerated. Even if a try and except block was used to enclose code with incorrect grammar, the interpreter would still throw a SyntaxError.

Traceback SyntaxError

When an erroneous syntax in Python code is encountered by the interpreter, SyntaxError is thrown, and a traceback is supplied with some important information to aid in tracking the issue. Here's a Python script using the wrong syntax:

Line 4 of the dictionary literal contains a syntax error. There is no comma after 'Jim' in the second entry. Running this code in its current form would result in the following error message:

According to the traceback message, the fault does not line 4, but line 5. The Python interpreter highlights any errors in the syntax. However, it can only accurately pinpoint the moment when a problem was first discovered. If you receive a SyntaxError traceback and the code it refers to appears to be correct, works backward until you figure out what is wrong in your code.

In the example above, depending on what comes after it, it is not an issue to leave out the comma. A missing comma following the name of the person in line 5 ('michael') is not an issue. The interpreter, on the other hand, can only point you in the direction of the first thing it couldn't understand.

A SyntaxError traceback contains a few features that can assist you to figure out where your code has the incorrect syntax:

  • The name of the file containing the invalid syntax.
  • A description of the error, including the line number and exact location in the code that caused it.
  • Caret () on the line below the repeated code shows the problematic position.
  • The error message appears after the exception type SyntaxError, which may provide useful information for solving the problem.

There was a caret in the dictionary key at the end of Michael's closing quotation in file name theofficefacts.py, line number 5. The SyntaxError traceback may not be the root cause of the problem, but it will be the first time the interpreter fails to understand the syntax.

Python also throws two additional exceptions. They're similar to SyntaxError, but they're called something else:

  • IndentationError
  • TabError

Both of these exceptions derive from the class named SyntaxError, although they only apply in special cases involving indentation. When your code's indentation levels aren't aligned, an IndentationError is thrown. When tabs and spaces are used together in the same file, a TabError is thrown. A detailed discussion of these exclusions will be provided in the next section.

Which are the common syntax errors?

When you first run into a SyntaxError, it's a good idea to look into what went wrong and how you may correct the Python code's syntax. Some of the most common causes and fixes for SyntaxErrors are covered in the following sections.

Misuse of Assignment Operator (=)

In Python, there are several situations where you won't be able to assign values to objects. Assigning to literals and calling functions are two instances. You can see a few examples of this in the code block below, along with the SyntaxError tracebacks that result:

In the first example, the value 5 is assigned to the len() method. In this case, the SyntaxError warning is really valuable. It notifies you that you can't give a function call a value.

In the third and second examples, literals are assigned a string and an integer, respectively. For other literal values, the same rule applies. According to the traceback messages, the issue appears to be caused by trying to set the value of a literal to a specific value.

Take notice that the traceback fault isn't indicated in the previous samples by caret () and repeated code line. You'll notice a different error and traceback depending on whether REPL is being used or running the code from a file. As you've seen in earlier examples, an error caret would indicate where the problem would be in the file if the code was contained therein.

Using a function or assigning a literal value is extremely unlikely. This can be caused by removing one equal symbol (=) from the expression, which transforms the assignment into a comparison. A comparison like the one that follows might be useful:

A Boolean expression may be the cause of Python's warning that you're assigning a value to a variable that cannot be assigned to. While assigning an object's value (which you'll learn about in the next section), you may encounter this same problem.

Misuse of Python Keywords, Spelling Errors, and Omissions

When using Python, you'll want to stick to terms that have a specific meaning. Identifiers, variables, and function names cannot contain any of the words listed below. The only environment in which they can be utilized is within Python.

There are three typical ways that you might improperly utilize keywords:

  • Spelling error of a keyword
  • Omission of a keyword
  • Use of keywords incorrectly

If you misspell a term in your Python code, then you’ll get a SyntaxError. For instance, this happens when you spell the keyword "for" wrong:

There is a notification that reads "SyntaxError: incorrect syntax," but it doesn't provide much assistance. Using the traceback, you can go back to the point where Python first discovered an issue. To fix this problem, check your Python code to make certain that all of its keywords are spelled correctly.

Another typical issue with keywords is when you overlook them altogether:

Because of this, traceback does its best to direct you to where you should be looking. You'll see that the for-loop syntax lacks the in keyword when you step back from the caret.

You could potentially make a mistake with a Python keyword that is protected. The use of keywords is restricted to specific contexts. The incorrect syntax will result if you use them incorrectly.

'Continue' or 'break,' for example, are frequently used outside of a loop. When you're working on something and move logic out of a loop, it's easy to run into this problem:

Python does an excellent job of describing what's wrong in this scenario. The messages "'break' outside loop" and "'continue' not suitably in the loop" will guide you to the next step. Python would have the caret pointing to the incorrect sentence if the code was stored in a file instead.

Another possibility is to use a keyword to construct a function or to attach a Python keyword to a variable:

If you attempt to set the value of pass or create a new function called pass, you will receive a SyntaxError and an "invalid syntax" message.

Because the code appears to be fine from the outside, it may be tough to correct this type of poor syntax with Python programming. A SyntaxError may occur even if your code appears to be correct. In this case, look up the variable or function name in the Python version's keyword list.

Every time a new version of Python is released, the list of protected keywords grows. The term "await" has been introduced to the list of keywords in Python 3.7 and is now available as a variable or function name in Python 3.6. Any attempt to use await as an object name in Python 3.7.1 or later will result in an error.

Another difference between Python 2 and Python 3 is the print function:

A value can't be provided for print in Python 2, since it is a keyword. The built-in function can take values in Python 3, though.

Running the following command in any Python version will return a list of keywords.

In addition, the keyword offers the relevant keyword .iskeyword(). Using the one-liner below, you can rapidly verify the value of the pass variable.

Your identification will be immediately flagged as either keyword or not by this code.

Missed brackets, parentheses, and Quotes

A missing or mismatched terminating parenthesis, bracket, or quotation is frequently the root of erroneous syntax in Python code. As a result, it may be difficult to tell nested parentheses from the rest of the text, especially in long lines. It is possible to discover mismatched or missing quotations with the use of tracebacks provided by Python.

The traceback leads to the wrong code, which includes a t' after a single closing quotation. One of two adjustments can be made to correct this:

  • Using backslash to escape a single quote ('don\'t')
  • Using double quotes to surround the entire string ("don't").

The failure to terminate the string is also a common problem. Regardless of whether a string is double-quoted or single-quoted, the following is true:

In the traceback, the caret now points straight to the incorrect code. "EOL during scanning string literal" is explicit and helpful in identifying the issue in the SyntaxError notice. Before a string may be ended, an interpreter must reach the end of a line. To remedy this, add a quote at the end of the string that is identical to the one you used at the beginning. In this scenario, there would be a double quotation (").

Syntax errors can also be caused by missing quotes from statements within the f-string:

An error has occurred when it comes to f-string output. The double quotation marks at the end of the age dictionary reference have been left out. The resulting traceback is as follows:

The f-string contains the problem, and Python tells you about it. The error message "unterminated string" also clarifies the situation. The caret simply symbolizes the beginning of the f-string in this example.

This isn't as beneficial as when the caret points to the f-issue string's area, but it does assist narrow down where you need to search. Inside that f-string, there's an unterminated string. All you have to do now is figure out where. Remove the error by including all of the f-string quotes and brackets inside.

Except for removing parenthesis and brackets, the scenario is essentially the same. An error message will appear if the ending square bracket of a list is left out in Python. There are, however, several variations on this theme. The first option is to leave out the final bracket:

There will be an error message when you run the above code when there is a problem with the print() call.

Print(foo()) returns a list with three items: 1, 2, and 3 according to Python. It employs whitespace to logically order things, and because 3 and print(foo()) don't have a comma or bracket between them, Python combines them as the list's third entry.

After the final item in the list, you can use a trailing comma instead of a closing square bracket:

Now you receive a different traceback

Previously, 3 and print(foo()) were combined into one component, but now there is a comma between them. The print(foo()) command has been added to this list because Python has reached its conclusion of the file without a final encasement. An EOF error was returned by Python, which was expecting a different outcome.

The repeated line and caret aren't very useful in this scenario because Python was anticipating a closing bracket (]). Python has a hard time detecting missing brackets and parenthesis. Starting with the caret and working backwards is sometimes the only way to figure out what's missing or incorrect.

Conclusion

Congratulations! You've made it to the end of this tutorial. You've been exposed to a few reasons why you may face syntax problems when programming in Python, and so in the following chapter, we will look at a few additional reasons for syntax issues. With this, you can create Python code with fewer syntax problems. Let's meet in the next tutorial for more.


JLCPCB – Prototype 10 PCBs for $2 (For Any Color)

China’s Largest PCB Prototype Enterprise, 600,000+ Customers & 10,000+ Online Orders Daily
How to Get PCB Cash Coupon from JLCPCB: https://bit.ly/2GMCH9w

Syed Zain Nasir

I am Syed Zain Nasir, the founder of <a href=https://www.TheEngineeringProjects.com/>The Engineering Projects</a> (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry. <a href=https://plus.google.com/+SyedZainNasir/>My Google Profile+</a>

Share
Published by
Syed Zain Nasir