How to Fix Invalid Syntax Error in Python

54

In this tutorial, you will learn how to fix invalid syntax error in Python. In any programming language, syntax specifies the arrangement of words that creates valid statements that can be understood by the interpreter to execute. It is the same as grammar rules in English (any language) that helps us to convey the meaning of sentences we framed to others.

Syntax Errors occur in any programming language whenever a programmer does not follow the syntax rules while coding. In Python, syntax exceptions are raised when the parser encounters syntax errors in the source code.

In general, we can say that syntax error exceptions occur when the interpreter doesn’t understand what the programmer has asked it to do. It is one of the most common errors that any programmer can experience.

Also ReadHow to Fix Unexpected EOF While Parsing Error In Python

Let’s look into cases when the interpreter throws the Syntax error exception.

How to Fix Invalid Syntax Error in Python

The interpreter will raise syntax error exceptions when programmers incorrectly use the print() function. Generally, the programmers who switched from Python 2 to Python 3 will face this error.

In Python2, we do not need to use brackets after the print function. But in Python3, programmers should specify brackets using the print() function.

Also ReadHow To Copy List in Python

Let’s look into an example program that throws a syntax error due to the wrong usage of the print function.

Code

# printing the text using print function
print "CodeITBro"

Output

File "<ipython-input-5-955fb7a533bb>", line 2
print "CodeITBro"
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("CodeITBro")?

Here the SyntaxError exception occurred due to missing parentheses in the print function. You can resolve this error by specifying the parentheses in the call to print method.

Also Read10 Best Programming Apps To Learn Python

Error Fix Code

print("CodeITBro")

Output

CodeITBro

Also ReadPython Program To Reverse A Number

Missing Closing Symbols

Sometimes we use some symbols like ‘ ’, “ ”, [ ], { } to declare a string, list, dictionary etc. At the time of declaration, programmers sometimes forgot to close any symbols. At that time, the Python interpreter will throw SyntaxError due to missing closing symbols.

Let’s look into a few example programs which throw syntax errors due to missing closing symbols.

Code-1

word = "CodeITBro

Here the SyntaxError is thrown because of missing closing quotes in the string declaration. So this error is fixed by adding the closing quotes.

Output

File "<ipython-input-1-b885ef35ea88>", line 1
word = "CodeITBro
^
SyntaxError: EOL while scanning string literal

Also ReadPython Program to Find Sum of Digits [5 Methods]

Error Fix Code

word = "CodeITBro"
print(word)

Output

CodeITBro

Code-2

lang = ["C", "C++", "Java", "Python"

Output

File "<ipython-input-3-b750549d9c30>", line 1
lang = ["C", "C++", "Java", "Python"
^
SyntaxError: unexpected EOF while parsing

Here the SyntaxError is thrown because of missing closing brackets in the list declaration. So this error is fixed by adding the closing brackets.

Also ReadPython Program To Check If A Number Is a Perfect Square

Error Fix Code

lang = ["C", "C++", "Java", "Python"]

Missing Punctuations

It is one of the most common mistakes made by programmers while coding. Let’s look into an example program that throws a SyntaxError due to missing punctuation.

Code

dictOfValues={1:"One",
2:"Two"
3:"Three"}
Output
File "<ipython-input-5-c7811add4002>", line 3
3:"Three"}
^
SyntaxError: invalid syntax

Here the error shows in line 3, but the actual error consists in line number 2, i.e., missing punctuation.

Also ReadIncrement and Decrement Operators in Python

Error Fix Code

dictOfValues={1:"One",
2:"Two",
3:"Three"}
print(dictOfValues)

Output

{1: 'One', 2: 'Two', 3: 'Three'}

Also ReadPython Dictionary Length [How To Get Length]

Misspelling Keywords

It is also a common SyntaxError that occurs when a programmer wrongly spells keywords in the code. Keywords are reserved words in Python used to define syntax and structure. A few of them are if, else, for, while, in, not, and, etc.

Let’s look into an example program that throws a SyntaxError due to keyword misspelling.

Code

number=4
if(number%2==0):
print('Even')
esle:
print('Odd')

Output

File "<ipython-input-1-ee4275bc7fd3>", line 4
esle:
^
SyntaxError: invalid syntax

In the above code, the else keyword after the if statement is wrongly spelled as esle. So that was the reason for the Syntax error.

Also ReadHow To Concatenate Arrays in Python [With Examples]

Error Fix Code

number=4
if(number%2==0):
print('Even')
else:
print('Odd')

Output

Even

Also ReadWhat Does The Python Percent Sign Mean?

Keyword Misusage

Misusing keywords in the source code also throws the SyntaxError. One such case is using a break keyword outside the loop. Here is an example of when the SyntaxError exception is thrown when keyword misusage happens.

Code

number=9
flag=0

# is prime or not
for i in range(3,number):
if(number%i==0):
flag=1
break
if(flag==1):
print(number," is not a Prime number")
else:
print(number," is a Prime number")

Output

File "<ipython-input-3-46dcf438a738>", line 11
else:

^
SyntaxError: 'break' outside loop

Due to the wrong usage of the break keyword. Brek keyword should be present inside of the loop.

Also ReadHow to Create an Empty Array In Python

Error fixed code

number=9
flag=0

# is prime or not
for i in range(3,number):
if(number%i==0):
flag=1
break
if(flag==1):
print(number," is not a Prime number")
else:
print(number," is a Prime number")

Output

9 is not a Prime number

Also ReadWhat Is Python Used For? Applications of Python

SyntaxError due to specifying data types

Python is a dynamically typed language. So if the programmer specifies the data type to the variable like int n=100, then the interpreter will throw a SyntaxError. Unlike programming languages like C, C++, and Java, there is no necessity to specify the data type in Python as it is dynamically typed.

An example program throws SyntaxError when the data type is specified or a variable.

Code

int n = 4
Output
File "<ipython-input-1-ad0c31185505>", line 1
int n = 4
^
SyntaxError: invalid syntax

As Python is a dynamically typed programming language, there is no need to specify the data type while defining/declaring. So the SyntaxError can be cleared by the following code.

Error Fixed Code

n = 4

Also ReadHow To Display A Calendar In Python

Indentation Errors

Generally, programming languages like C, C++, Java, etc. use flower braces to specify the scope of variables/lines of code.

But unlike other programming languages, Python uses indentation as a coping mechanism. Typically programmers use a tab space or 2 (or) 4 spaces. So it is crucial to maintain consistent indentation in the entire code.

Let’s look into an example program that throws a syntax error due to wrong indentations.

Code

number = 1

while(number < 10):
result=number
number=number+1
print(result)

Output

File "<tokenize>", line 5
number=number+1
^
IndentationError: unindent does not match any outer indentation level

Here the indentation error occurred due to uneven/inconsistent indentation in the source code. You can fix this error by maintaining a consistent indentation across the code.

Also ReadHow To Sort a List of Tuples in Python

Error Fix Code

number = 1

while(number < 10):
result=number
number=number+1

print(result)

Output

9

Also ReadArithmetic Operators in Python [With Examples]

Summary

So those mentioned above are the few cases when the Python Interpreter encounters the SyntaxError exception. In this tutorial, you learned how to fix invalid syntax error in Python. The standard errors, like missing closing symbols, misspelling keywords, etc., can be reduced by using any IDEs (Integrated Development Environments) while coding.