Skip to content

Syntaxerror: invalid syntax (solved)

You just finished typing out your Python code, hit run, and your screen shows “SyntaxError invalid syntax”.

This is a common error that plagues both experienced and new Python developers alike. As always, the error message will give you most of the information you need to debug the problem.

How do I fix SyntaxError invalid syntax in Python?

The assignment operator

Always double check you are using appropriate operators. If not, you are likely to get a “SyntaxError: invalid syntax” error.

The following code is invalid:

a 3

On the other hand, the following code is correct:

a = 3

Python keyword error

Avoid using Python keywords as identifiers in your code.

Here is a tip. Any word you use to trigger something in Python is probably a reserved word.

Opening and closing symbols

If you get a “syntax error invalid syntax” message that does not give you more details, this is one of the few things to check.

Carefully go through the line in question, as well as the lines near it and those associated with that line. Wherever you opened a certain symbol, make sure you closed it.

Also double check you used the same symbol on both ends of the statement. For example, the following code will generate an error:

name = ‘Andre”

This is because the string starts with a single quote but ends with a double quote. These two do not match.

The same rule applies to brackets and triple quotations.

Escape characters

Escape characters is a way of letting Python know it should consider the character after the backslash (\) under a different context.

Here is an example of how the backslash works:

x = 'Is that John\'s apple?'

Python now knows the apostrophe in John’s is indeed an apostrophe, and not a closing single quote.

Incorrect dictionary value assignment operator

Always use a colon when assigning values to keys.

For example, the following code is correct:

human = {
‘name’: ‘David’,
‘age’: ‘25’,
‘country’: ‘South Africa’
}

Indentation errors

There are a few guidelines you can follow to prevent/fix this error.

Always indent your code when working with code blocks. Code blocks include:

  • conditional statements
  • loops
  • functions
  • classes

Make sure your indentation is consistent within the same code block. If the second line in your block starts with four white spaces and the next starts with six, Python will assume the third line is a subblock. This can trigger an error.

Similarly, decide on whether you are going to use white spaces or tabs in your code. Stick by whatever choice you make. Switching between tabs and spaces within the same code block will generate an error.

Function calling and defining mistakes

Double check the following when defining functions in Python:

  • You start with the def keyword.
  • The name of the function is not a reserved keyword.
  • There is a set of round brackets () after the function name.
  • The closing round bracket is immediately followed by a colon (
  • Everything in the function is properly indented.

Here is an example of a good function:

def myname():
Print(“Andre Davis”)

Remember to be precise when calling a function, down to capitalization. Myfunc and myfunc are not the same.

Here is how we might call the function we created above:

myname()

Upgraded features

These are probably the hardest errors to catch. This is especially true if you are only familiar with Python 3.

You are using invalid code that does not run on Python 3 if your code contains any of the following:

  • print without round brackets-
  • xrange: instead of range
  • file instead of open

Here is an extensive list of changes you need to watch out for.

Type the following in your command prompt to find out the Python version your machine is running:

Python –version.

Download the latest version of Python from the official site.

This guide is going to explore the following:

  • The nature of syntax errors.
  • The cause of most syntax errors.
  • How to fix syntax errors.

Python errors

Python errors fall into three broad categories. They are:

  • syntax errors
  • logic errors
  • exceptions

While the other two are important to know, the rest of this guide is going to focus on syntax errors.

What does SyntaxError invalid syntax mean?

Syntax errors are mistakes made by the programmer when writing code. These mistakes prevent the program from executing. Most syntax errors are a result of incorrectly using certain characters and symbols.

Syntax is where programming languages have much in common with spoken languages. Omitting a punctuation mark or a noun can change the entire meaning of a sentence.

For example, “scared away the python.” Makes absolutely no sense. Who or what exactly scared away the python?

Another example we can use is your friend’s phone number. Changing a single digit means you will either dial a number that does not exist, or call someone else.

Similarly, the inappropriate use of characters, symbols, and indentations in Python leads to programs that do not execute.

Just like we follow grammar rules in English, we need to follow syntax rules when coding in Python.

Understanding what error messages mean

You cannot troubleshoot errors if you do not know what they mean, and you are also unable to understand the error message.

Here is an example of a syntax error:


x = "My name is David."
print x)

The following error occurs when you run the above code:

File "C:\Users\Username\Desktop\Python\filename.py", line 2  print x)

SyntaxError: Missing parentheses in call to 'print'. Did you mean print(x))?

The above tells you the following:

  • The name of the file where the error is occurring (File "C:\Users\Username\Desktop\Python\tfilename.py").
  • The problematic line within that file (line 2).
  • The error type and some times, the actual error (SyntaxError: Missing parentheses in call to 'print'.)
  • Sometimes suggestions on how to fix the error (Did you mean print(x)))

You will almost always get the line number where the error is occurring. The actual error will in most instances be found in any of the following:

  • The line number that comes with the error message.
  • The few lines preceding or after the error line.
  • The line in which you created the variable / function failing to execute.
  • Any line associated with the line number in the error message.

Why am I getting syntax errors

There are any number of reasons why you might be getting syntax errors. Here are some.

A missing assignment operator

The assignment operator (=) assigns a value to a variable. It lets the system know that value is represented by that specific variable.

Here are some examples:

x = 5 #This means the value “5” has been stored in the variable “x”.

name = “David” #This means David is now stored in variable name.

Syntax errors can occur when you forget to use the assignment operator (=)

Consider the following code:

a 3
print (a)

The above code will generate an error. This is because there is no assignment operator (=), and the program does not know where to find the value stored in a.

Python keyword error

Most programming languages have lists of reserved words that cannot be used as names for your variables, functions, classes, etc. This is because these words trigger other functionalities / features of the programming language. These words are known as keywords.

Here are some examples of Python keywords:

  • break
  • class
  • continue
  • if
  • else
  • false
  • for
  • global
  • true
  • while
  • return

The following code will generate an error:

if = "My name is Arthur."

print (if)

The above code does not work because Python assumes whatever comes after (if) is an if statement.

Opening and closing symbols

The spoken language has certain punctuation rules that help us understand sentences. A capital letter tells us a sentence is starting, while a period alerts us the sentence has ended. A question mark tells the reader the statement is a question mark, while a series of commas informs us we are looking at a list of items.

Similarly, opening and closing symbols tell the program how to handle code inside these symbols. Therefore, the program does not know how to execute if an error has been made with these symbols.

For example, strings are always enclosed inside quotation marks. This lets the program know the values are strings.

Likewise, function values and variables are enclosed inside parenthesis, list items are inside square brackets, dictionaries are placed between braces, and so on.

The following code will generate an error:

act = I am programming in Python"
print (act)

The following code will also generate an error:

print "hello world!"

Not escaping characters

English, along with many languages, has words that mean more than one thing. The true meaning always depends on the context. Similarly, characters and symbols can serve more than one function in Python.

For example, the apostrophe (‘) is used to open and close single quotes. The same character is used to indicate ownership (Merlin’s), or to shorten/connect words (don’t instead of do not).

Consider the following code:

x = 'Is that John's apple?'

Python does not know if the apostrophe in John’s is the end of the current string. Therefore, the above code will generate a SyntaxError invalid syntax error.

Incorrectly assigning values to dictionary keys

Dictionaries are variables that allow us to store other variables inside them.

We already looked at how the assignment operator (=) should be used to assign values. A quirk of Python is that we use a colon ( instead of an (=) sign to assign values to dictionary keys.

Consider the following code:

Place = {
‘continent’ = ‘Africa’,
‘country’ = ‘Namibia’,
‘city’ = ‘Windhoek’,
}

The first part of the above code is correct (place =).

The part between braces (‘country’ = ‘Namibia’) is wrong and will generate an error.

Indentation errors

Most programming languages use semicolons to separate code snippets. As a result,  spaces do not always matter.

For example, in PHP:

echo “Hello there”; echo “What is your name”; exit();

And:

echo “Hello there”;

echo “What is your name”;

exit();

are exactly the same.

Python is different. Code is separated by tags and indents. As a result, the amount of space you leave at the beginning of a line of code can prevent your program from running.

Any of the following practices can cause an error:

  • Inconsistent number of spaces between code within the same code block.
  • Interchangeably using white space and tabs in the same code block.
  • Not indenting when dealing with code blocks.

For example, the following code will generate an error:

x = 5
if x == 5:
print ("They are the same")

Function calling and defining mistakes

Functions are blocks in which you can store data and call it again later. One of the biggest advantages of functions is you do not need to write the same code over and over.

A syntax error can occur when you incorrectly define a function, or when you call a function using the wrong name.

The following code will generate an error:

def learningfunction:
print ("I am learning to avoid Python errors")

The following code will also generate an error:

def learningfunction():
print ("I am learning to avoid Python errors")
learnfunc()

Upgraded features

Python is regularly updated and upgraded, just like any tech product. These updates sometimes result in syntax changes.

For example, print was an ordinary keyword before Python 3. As of Python 3, print is now a function. This means whatever you want to display has to be between round brackets.

Conclusion

There are several reasons you might get a syntax error. They include:

  • Inappropriate use of assignment operators.
  • Using python keywords as identifiers.
  • Incorrect application of opening and closing marks.
  • Not escaping characters.
  • Using (=) instead of ( when assigning values to dictionary keys.
  • Indentation errors.
  • Making errors when defining or calling functions.
  • Ignoring coding updates that result from Python upgrades.

Comments

Latest

As an Amazon Associate we earn from qualifying purchases.