Syntax Error

A syntax error occurs when Python’s parser encounters something it doesn’t expect to see in your code. This usually happens when there’s a violation of Python’s syntax rules while coding.

Code Example of Syntax Error

Here’s a simple example of syntax error:

1print("Hello, World!)

In the above line of code, we forgot to close the quotation marks. As result Python’s parser will raise a SyntaxError.

Correct code:

1print("Hello, World!")

Once we correct the syntax error by adding the closing quote, the code will run successfully and print “Hello, World!” to the console.

Note

While Python’s interactive interpreter or any other Python-aware text editor or IDE might indicate such errors as you type, sometimes, errors are not detected until the code is run.

Detecting Syntax Errors

Python aims to be a very readable language, hence its syntax rules are designed with clarity in mind. A line of Python code is supposed to resemble a line of English to a certain degree. When a line of Python code doesn’t meet the syntax rules, Python’s parser doesn’t know how to interpret that line, and a SyntaxError is the result.

Typically, when a syntax error is encountered, Python will print an error message that includes the file name and line number where the problem occurred, as well as a small ‘pointer’ that indicates the earliest point in the line where the error was detected.

If the error occurs while parsing the first script passed to Python, only the error message is printed. No stack trace is printed to the console.

If the error occurs in a script being imported by another script, a full traceback is produced, which includes the context of the call to the import statement.

Did you know?

Even though syntax errors might seem daunting at first, they are your friends rather than your enemies. They are your built-in debugging assistant, guiding you towards understanding and fixing the problem.