SyntaxError: A Step By Step Troubleshooting Guide!

In this article, let us learn what causes SyntaxError and see how we can fix that and get our code up and running again!

Troubleshooting any errors will include the following steps

  • Step#1: Understand the error and its causes
  • Step#2: Figure out which of the causes actually led to the error in your particular case
  • Step#3: Apply the Fix, and test your code to confirm.
  • Step#4: Party!

Let us start by understanding the SyntaxError and its causes!

Understanding SyntaxError & Its Root Cause

What is Syntax?

The word syntax means “a collection of rules to structure the code

Just like languages have “grammar to decide whether a particular sentence is correct or not, programming languages have “syntax” to decide whether a line of code is written the way it is supposed to!

Grammatical mistakes lead to incorrect sentences, syntactical mistakes lead to SyntaxError!

Why do we need it?

When we speak, if we make a grammatical error, odds are the person listening to us will still understand the point we were trying to make. That is because human communication involves not just words and sentences, it also involves things like

  • tone of voice
  • Facial expressions and
  • Body language

Also add the fact that humans are intelligent beings, so they can figure things out based on the situation.

Sadly all we have is words when we are communicating with computers, so we need to make sure that the orders we are giving are structured properly so that computers can fulfill our commands.

The code we write is converted into 0s and 1s before execution. This conversion is done with the help of the rules of any given programming language. One of these important rules is the Syntax of a given programming language.

Alright, enough theory, let’s look at an example!

Have a look at the following 2 programs.

if a == b:
    print("a is equal to b")

if a = b:
    print("a is equal to b")

Notice how similar they look at first glance but upon a close inspection, you would see that the 2 programs are different. (There is 2 “=” signs on the 1st one, and just one “=” sign on the second one)

In the first program, we are checking if the variable a is equal to the variable b and printing a message if they are.

If you run these programs by giving a and b some values, the first one will run just fine but the second program will lead to a SyntaxError.

This is because “==” is a comparison operator and is used to compare 2 values, while “=” is an assignment operator.

You can learn more about this fancy “==” operator here

Python syntax does not allow us to assign values to variables inside an if statement and hence we ended up with a SyntaxError!

A simple additional ‘equal to operator’(=) has totally changed the meaning of the code. That is the value of syntax!

What is SytaxError?

Before we get into that, let’s refresh our memories about exceptions:

What are exceptions and why do we need them?

Let us start with, why the name “exceptions”?

The program will run fine except for a few situations and these few “excepts” are called exceptions!

embeddedinventor.com

If the Python interpreter does not understand what we are trying to tell it to do, it will simply stop the execution of the program. These kinds of premature exits are called exceptions.

Hence, another way of looking at Exceptions is

Exceptions are controlled program crash by the interpreter

Paul Barry, Head first Python, O’Reilly

To avoid these crashes, we need to learn how to deal with these exceptions/ “bad situations” when they occur while our program is run.

We have an entire article dedicated to teaching beginners about exceptions that you can find in the link below

Exceptions in Python: Explained for Beginners!

One such Exception is SyntaxError Exception, which occurs when Python has no clue what we are trying to say since our grammar was incorrect!

Cause of SyntaxError

The mistakes that you can do while programming that lead to a SyntaxError range from incorrect indentation to mismatching quotes.

Here’s an example:

print('Hello World!")

Since the quotes around the string are not matching, it triggers a SyntaxError:

  File "/home/main.py", line 1
    print('Hello World!")
          ^
SyntaxError: unterminated string literal (detected at line 1)

Alright now that we have a basic understanding of SyntaxError, let’s dive into how to solve it and remove that pesky error message off your screen.

How to solve SyntaxError?

Before we get started here is a pro tip for you, to fix not just SyntaxError but any error in Python. Whenever your program crashes with an Exception, don’t panic! Take a deep breath and have a look at the huge wall of error text that just got printed on your screen!

There is a wealth of information contained in the error message, if you wish to learn the tricks then set aside 10mins of your time and read the following article!

Python: Details contained in an Exception

For visual learners out there we have also made an interesting video on that topic!

Coming back to the topic let us take a closer look at each of these causes so that you can figure out which one of these caused the problem for your particular case!

Using an IDE

If you’re coding using an IDE, solving a SyntaxError is quite straightforward. Most IDEs highlight code that has syntactical mistakes as you code, making them easy to spot and fix!

Here’s an example:

In the above line print”Hello World”  is incorrect because the print statement is missing the parenthesis. The correct code is print(“Hello World”) . You would see that the red underline disappears when we correct it:

Now of course, we can’t always rely on IDEs, knowing how to solve problems by yourself is essential if you wish to become a Python craftsman.

So let’s look at a few more examples to get an intuitive feel for syntax errors!

Example#1: Misspelling:

Misspelling a reserved keyword can lead to a SyntaxError, here’s an example:

iff True:
    print("Hello world!")

OUTPUT:

  File "/home/main.py", line 1
    iff True:
        ^^^^
SyntaxError: invalid syntax

To fix it, double-check your code and correct out any misspellings!

Example#2: Invalid indentation:

Using invalid indentation can also trigger a SyntaxError, here’s an example.

if True:
print("Hello world!")

OUTPUT:

  File "/home/main.py", line 2
    print("Hello world!")
    ^
IndentationError: expected an indented block after 'if' statement on line 1

Always remember to follow correct indentations!

Python uses indentations to determine the grouping of statements, so an invalid or illogical grouping is bound to raise a SyntaxError!

Example#3: Improper usage of special characters

Alternatively, using the special characters incorrectly is another way that leads to a SyntaxError.

Let’s see an example to see what I mean by “Improper usage of special characters”!

In the following example, the colon is missing after we define the if statement

if True
    print("Hello world!")

OUTPUT:

  File "/home/main.py", line 1
    if True
           ^
SyntaxError: expected ':'

Here’s another example where we make the mistake of having unbalanced parentheses.

if True:
    print("Hello world!"))

OUTPUT:

  File "/home/main.py", line 2
    print("Hello world!"))
                         ^
SyntaxError: unmatched ')'

And lastly, incorrectly using the ‘=’ sign:

num = 10

if num = 10:
    print("num is equal to 10!")
else:
    print("num is not equal to 10!")

OUTPUT:

  File "/home/main.py", line 3
    if num = 10:
       ^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

Notice how the output gives a hint as to what might have gone wrong! This happens from time to time, you can use these hints to debug your code!

Making simple mistakes like this is part and parcel of programming, but understanding how to fix mistakes will surely make your life easier!

I hope by now the SyntaxError has been fixed and you have tested and confirmed the fix too!

According to our troubleshooting roadmap, there is just one more pending step here, which is to celebrate our win today!!

Also it is worth noting that SyntaxError is not one of the most common exceptions you will run into in your daily life as a Python developer. Instead, you need to focus on 7 other errors mentioned in the article below if you wish to gain mastery in Python!

7 Most Common In-Built Exceptions in Python!

If you are a visual learner here is a YouTube video that we made on that same topic!

And with that, I will end this article.

I hope you enjoyed reading this article and found it useful!

Feel free to share it with your friends and colleagues!

If your thirst for knowledge has not been quenched yet, here are some related articles that might spark your interest!

Related Articles

Exceptions in Python: Explained for Beginners!

Python Lists: Everything You Need To Know!

append vs extend in Python Lists: Explained with Examples!

Thanks to Namazi Jamal for his contributions in writing this article!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn