In Python, SyntaxError exception occurs when a line of code is not properly formatted according to the language's syntax. This includes misspelling keywords, forgetting a colon, forgetting to close parentheses or brackets, etc. 

a = [1, 2, 3)

Syntax Errors are the most common type of errors and beginners are more likely  to encounter them. Similarly they are also the easiest to identify and fix. The interpreter will usually tell you exactly where the syntax error is and what is causing it, making it easy to fix.

Unlike other type of exceptions in Python, It is not possible to handle SyntaxErrors using the try-except blocks except in some few cases. This is because, normally,  the interpreter parses the entire file before any statements is executed.  Thus the SyntaxError will be found and raised before the try-except blocks are executed.

try :
    #No colon at the end of function definition
    def func()
        print('hello')

except:
    print("The error was raised anyway")

//  File "<stdin>", line 3
//    def func()
//              ^
//SyntaxError: expected ':'

The few cases where we can effectively catch SyntaxErrors is when we are executing code dynamically using the exec() and eval() functions or during imports. For example:

code ="print(([1]"
try:
    exec(code)
except SyntaxError:
    print("Invalid syntax")

//Invalid syntax

Some Common causes

  • Inconsistent indentation: Python uses indentation to identify code blocks, each statement belonging to the same block must be at the same level of indentation. Otherwise, a syntax error will be raised.
  • Forgetting a comma  - Individual items in builtin container data types such as lists, sets, dictionaries and tuples are separated with commas.  In cases where we forget to add a comma  to separate the elements, a syntax error is raised.
  • Omitting a colon: If a colon is missing at the end of a statement such as an if, forwhile,etc.
  • Mis-matched brackets: Each bracket must have a corresponding closing brackets.  For example, a syntax Error will be raised if you close a parentheses with a curly brace.
  • Unbalanced quotation marks: Each opening quotation mark must have a corresponding closing quotation mark, otherwise a syntax error will be raised.
  • Incorrect use of keywords:  Each keyword has its own purpose and scope of application. If we use a keyword for other than the intended purpose or outside its scope of application, a Syntax error will be raised.
  • Incorrect use of operators : Like keywords, each operator has its own purpose, a syntax error is raised if we use an operator for other purposes. A common case is using "=' when we are intending to use "==" for comparison.

Syntax Error Examples

#unclosed Quotation mark
print("Hello, World!)
#unclosed bracket
print([1, 2, 3, 4)
#Incorrect use of a keyword
continue = True
#Omitting a comma
L = [1, 2, 3 4, 5, 6]
# incorrect use of an operator
if 1+1 = 2:
   print('1 + 1 is 2')
#Ommiting a colon
def func
   print("A syntax error!")
#Inconmsistent indentation
def func():
   a = 10
     b = 20

func()

How to avoid syntax errors

Syntax errors are relatively easy to avoid.  The following part shows how you can easily avoid them:

  1. Use an Integrated Development Environment / Code editor: Using an IDE or an editor is the most obvious way to mitigate syntax errors in your code. IDEs/editors usually shows you  the syntax errors in real-time, as well as suggests quick fixes as you type.
  2. Do not mix tabs and spaces for indentation -  Using tabs and spaces is both syntactically correct and valid form of indentation in Python. However, mixing tabs and spaces together in the same code can lead to hard-to-debug errors as the interpretation of whitespace varies between systems. And  as a result, many IDEs are not designed to detect and identify syntax errors resulting from mixing tabs and spaces. 
  3. Double-check your code as you type - Some syntax errors are rather trivial and with little effort you can easily identify them by reading through the code . Paying attention as you type will ensure that you get rid of unnecessary syntax errors.
  4. Use linting and formatting modules - Linting and formatting modules can easily identify errors in your code and even correct them for you. They are especially useful in cases where you are running programs interactively without editors and IDEs.  Such modules includes pylintpyflakespycodestyle,  and many others.