Python error fix

A runtime error is a type of error that occurs during program execution. Learn how to fix them.

A runtime error is a type of error that occurs during program execution. The Python interpreter executes a script if it is syntactically correct. However, if it encounters an issue at runtime, which is not detected when the script is parsed, script execution may halt unexpectedly.

What Causes Runtime Errors

Some of the most common examples of runtime errors in Python are:

  • Division by zero.
  • Using an undefined variable or function name.
  • Performing an operation on incompatible types.
  • Accessing a list element, dictionary key or object attribute that does not exist.
  • Accessing a file that does not exist.

Python Runtime Error Examples

Here’s a few examples of runtime errors in Python:

Division by zero

If a number is divided by zero in Python, a runtime error is raised:

print(100/0)

In the above example, a number is attempted to be divided by zero. Running the above code raises a ZeroDivisionError:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    print(100/0)
ZeroDivisionError: division by zero

Using an undefined variable or function name

A runtime error is raised if an attempt is made to access an identifier, such as a variable or function name, that is not declared previously:

print(myString)

In the above example, an undefined identifier myString is attempted to be accessed. Running the above code raises a NameError:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    print(myString)
NameError: name 'myString' is not defined

Performing an operation on incompatible types

If an operation, such as addition, multiplication etc., is performed between incompatible data types, a runtime error is raised:

myString = "Hello World"
myNumber = 100
print(myString + myNumber)

In the above example, a string is attempted to be concatenated with a number. Since these types are incompatible, a TypeError is raised when the above code is executed:

File "main.py", line 3, in <module>
    print(myString + myNumber)
TypeError: can only concatenate str (not "int") to str

Accessing a non-existent list element, dictionary key or object attribute

If an attempt is made to access a non-existent index or element in a list, dictionary or   object, a runtime error is raised.

numbers = [1, 2, 3]
print(numbers[3])

In the above example, an attempt is made to access an item in a list using an out-of-range index, which raises an IndexError:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(numbers[3])
IndexError: list index out of range.

Accessing a file that does not exist

If a file that does not exist is attempted to be accessed, a runtime error is raised:

open("myFile.txt", "r")

In the above example, a non-existent file myFile.txt is attempted to be opened in read-only mode, which raises a FileNotFoundError:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    open("myFile.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'myFile.txt'

How to Fix Runtime Errors in Python

To fix runtime errors in Python, the following steps can be taken:

  1. Identify the error message and note the specific problem being reported.
  2. Check the code for logical, mathematical or typographical errors.
  3. Ensure all identifiers are defined properly before being used.
  4. Make sure the correct data types are being used and are being used correctly.
  5. Verify that list items, dictionary keys, and other objects are being accessed using valid indices or keys.
  6. If necessary, consult the documentation for the relevant library or module.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!

In this article, we will highlight how to fix syntax errors in python but firstly it’s important to know what are syntax errors?

Syntax errors are defined as violations of rules and regulations to form a layout of a certain logic. Syntax of tools are the structures and the building blocks to program any software. Errors in the syntax are the most common type of occurring errors in any programming language, especially if one is not familiar with it.

Reserved keywords, built-in functions, spaces, punctuations, and other semantics required, to use python’s tools needs to be strictly written as they are advised to. If any violations in the syntax and your program will not compile.

fix syntax errors in python.

When you write your code, the interpreter compiles and converts the code into a format that can be understood by your machine. The code cannot be construed and parsed if there are any invalid syntax errors.

Syntax errors are detected while the program is being compiled, once any error is found, it will prevent the code from executing. Usually, the errors are self-explanatory and docent needs any special attention to fix them. While some errors are not as corporative.

The good thing about syntax errors is that compiler points out to where the problem might be.

Let’s look at some most common causes of syntax errors.

  • Misspelled reserved keywords
  • Missing required spaces
  • Missing quotes
  • Misuse of block statements (if-else, loops)
  • Missing assignment operator (=)
  • Invalid variables declaration
  • Invalid function calling or defining

We are mentioning strategies to fix syntax errors in python below:

error of misspelled reversed word.

The compiler threw an error message as “prin not defined”. It’s not defined as a user-defined or built-in keyword, therefore it confuses the compiler to where this word lies.

Missing required spaces

Unlike other programming languages, python has the requirement for an indented block. That is why many programmers have trouble wrapping this concept in the early stages.

fix syntax errors in python.

Most languages might’ve executed this code (ignoring the terminators), but not python.  The print statement in line 3 should have a space of a tab.

removal of white spaces to fix syntax errors in python.

Missing quotes

When missing quotes in a string, the compiler confuses the purpose of the string and doesn’t identify it. Note how the error is “name hi not defined”, even though it’s supposed to be a string, not a variable. The compiler mistook it as a variable not defined and nowhere guessed the possibility of a string

fix syntax errors in python.

Notice how the error changed to the literal error when a quote is added. The compiler recognized it as a string and END OF LINE error is thrown.

fix syntax errors in python.

Misuse of block statements ( if-else, loops)

This is similar to missing spaces in addition to the missing semicolon (:). Python has another rule to use a (:) while ending block statements like loops, if-else.

fix syntax errors in python.

The error is “invalid syntax”. Not very descriptive, that is why an if-else colon (:) is required to fix this bug. It’s the same with while blocks.

Missing assignment operator (=)

fix syntax errors in python.

Notice that the compiler is not throwing an error to indicate that the assignment

operator is being misused. But it’s trying to compare the variable game to the string “me”, finding undefined variable.

Invalid variables declaration

There are many ways to violate the variable naming convention. You cannot use special characters to expect underscore (_), or use a number at the beginning variable and many others.

shows the invalid error

Here is another invalid way to declare a variable.

invalid variable declaration error

Invalid function calling or defining

Like any other block statement, function declaration has also a syntax. Proper spaces and use of the colon (:) are necessary. Messing up with the syntax will prevent from execution. The following example shows an executable function without errors.

without error executable function.

Function calling has to have the required cautions to prevent bugs. The following error is caused by the argument provided which is not defined in the declaration.

error occured in function declaration

Conclusion

There are many syntax errors in python that are frustrating. Many errors are obvious and easily eliminated while some errors are confusing. In this article, many common syntax errors were discussed with explanations to the cause of their occurrence by performing some code snippets.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Identify Invalid Python Syntax

Python is known for its simple syntax. However, when you’re learning Python for the first time or when you’ve come to Python with a solid background in another programming language, you may run into some things that Python doesn’t allow. If you’ve ever received a SyntaxError when trying to run your Python code, then this guide can help you. Throughout this tutorial, you’ll see common examples of invalid syntax in Python and learn how to resolve the issue.

By the end of this tutorial, you’ll be able to:

  • Identify invalid syntax in Python
  • Make sense of SyntaxError tracebacks
  • Resolve invalid syntax or prevent it altogether

Invalid Syntax in Python

When you run your Python code, the interpreter will first parse it to convert it into Python byte code, which it will then execute. The interpreter will find any invalid syntax in Python during this first stage of program execution, also known as the parsing stage. If the interpreter can’t parse your Python code successfully, then this means that you used invalid syntax somewhere in your code. The interpreter will attempt to show you where that error occurred.

When you’re learning Python for the first time, it can be frustrating to get a SyntaxError. Python will attempt to help you determine where the invalid syntax is in your code, but the traceback it provides can be a little confusing. Sometimes, the code it points to is perfectly fine.

You can’t handle invalid syntax in Python like other exceptions. Even if you tried to wrap a try and except block around code with invalid syntax, you’d still see the interpreter raise a SyntaxError.

SyntaxError Exception and Traceback

When the interpreter encounters invalid syntax in Python code, it will raise a SyntaxError exception and provide a traceback with some helpful information to help you debug the error. Here’s some code that contains invalid syntax in Python:

 1# theofficefacts.py
 2ages = {
 3    'pam': 24,
 4    'jim': 24
 5    'michael': 43
 6}
 7print(f'Michael is {ages["michael"]} years old.')

You can see the invalid syntax in the dictionary literal on line 4. The second entry, 'jim', is missing a comma. If you tried to run this code as-is, then you’d get the following traceback:

$ python theofficefacts.py
File "theofficefacts.py", line 5
    'michael': 43
            ^
SyntaxError: invalid syntax

Note that the traceback message locates the error in line 5, not line 4. The Python interpreter is attempting to point out where the invalid syntax is. However, it can only really point to where it first noticed a problem. When you get a SyntaxError traceback and the code that the traceback is pointing to looks fine, then you’ll want to start moving backward through the code until you can determine what’s wrong.

In the example above, there isn’t a problem with leaving out a comma, depending on what comes after it. For example, there’s no problem with a missing comma after 'michael' in line 5. But once the interpreter encounters something that doesn’t make sense, it can only point you to the first thing it found that it couldn’t understand.

There are a few elements of a SyntaxError traceback that can help you determine where the invalid syntax is in your code:

  • The file name where the invalid syntax was encountered
  • The line number and reproduced line of code where the issue was encountered
  • A caret (^) on the line below the reproduced code, which shows you the point in the code that has a problem
  • The error message that comes after the exception type SyntaxError, which can provide information to help you determine the problem

In the example above, the file name given was theofficefacts.py, the line number was 5, and the caret pointed to the closing quote of the dictionary key michael. The SyntaxError traceback might not point to the real problem, but it will point to the first place where the interpreter couldn’t make sense of the syntax.

There are two other exceptions that you might see Python raise. These are equivalent to SyntaxError but have different names:

  1. IndentationError
  2. TabError

These exceptions both inherit from the SyntaxError class, but they’re special cases where indentation is concerned. An IndentationError is raised when the indentation levels of your code don’t match up. A TabError is raised when your code uses both tabs and spaces in the same file. You’ll take a closer look at these exceptions in a later section.

Common Syntax Problems

When you encounter a SyntaxError for the first time, it’s helpful to know why there was a problem and what you might do to fix the invalid syntax in your Python code. In the sections below, you’ll see some of the more common reasons that a SyntaxError might be raised and how you can fix them.

Misusing the Assignment Operator (=)

There are several cases in Python where you’re not able to make assignments to objects. Some examples are assigning to literals and function calls. In the code block below, you can see a few examples that attempt to do this and the resulting SyntaxError tracebacks:

>>>

>>> len('hello') = 5
  File "<stdin>", line 1
SyntaxError: can't assign to function call

>>> 'foo' = 1
  File "<stdin>", line 1
SyntaxError: can't assign to literal

>>> 1 = 'foo'
  File "<stdin>", line 1
SyntaxError: can't assign to literal

The first example tries to assign the value 5 to the len() call. The SyntaxError message is very helpful in this case. It tells you that you can’t assign a value to a function call.

The second and third examples try to assign a string and an integer to literals. The same rule is true for other literal values. Once again, the traceback messages indicate that the problem occurs when you attempt to assign a value to a literal.

It’s likely that your intent isn’t to assign a value to a literal or a function call. For instance, this can occur if you accidentally leave off the extra equals sign (=), which would turn the assignment into a comparison. A comparison, as you can see below, would be valid:

>>>

>>> len('hello') == 5
True

Most of the time, when Python tells you that you’re making an assignment to something that can’t be assigned to, you first might want to check to make sure that the statement shouldn’t be a Boolean expression instead. You may also run into this issue when you’re trying to assign a value to a Python keyword, which you’ll cover in the next section.

Misspelling, Missing, or Misusing Python Keywords

Python keywords are a set of protected words that have special meaning in Python. These are words you can’t use as identifiers, variables, or function names in your code. They’re a part of the language and can only be used in the context that Python allows.

There are three common ways that you can mistakenly use keywords:

  1. Misspelling a keyword
  2. Missing a keyword
  3. Misusing a keyword

If you misspell a keyword in your Python code, then you’ll get a SyntaxError. For example, here’s what happens if you spell the keyword for incorrectly:

>>>

>>> fro i in range(10):
  File "<stdin>", line 1
    fro i in range(10):
        ^
SyntaxError: invalid syntax

The message reads SyntaxError: invalid syntax, but that’s not very helpful. The traceback points to the first place where Python could detect that something was wrong. To fix this sort of error, make sure that all of your Python keywords are spelled correctly.

Another common issue with keywords is when you miss them altogether:

>>>

>>> for i range(10):
  File "<stdin>", line 1
    for i range(10):
              ^
SyntaxError: invalid syntax

Once again, the exception message isn’t that helpful, but the traceback does attempt to point you in the right direction. If you move back from the caret, then you can see that the in keyword is missing from the for loop syntax.

You can also misuse a protected Python keyword. Remember, keywords are only allowed to be used in specific situations. If you use them incorrectly, then you’ll have invalid syntax in your Python code. A common example of this is the use of continue or break outside of a loop. This can easily happen during development when you’re implementing things and happen to move logic outside of a loop:

>>>

>>> names = ['pam', 'jim', 'michael']
>>> if 'jim' in names:
...     print('jim found')
...     break
...
  File "<stdin>", line 3
SyntaxError: 'break' outside loop

>>> if 'jim' in names:
...     print('jim found')
...     continue
...
  File "<stdin>", line 3
SyntaxError: 'continue' not properly in loop

Here, Python does a great job of telling you exactly what’s wrong. The messages "'break' outside loop" and "'continue' not properly in loop" help you figure out exactly what to do. If this code were in a file, then Python would also have the caret pointing right to the misused keyword.

Another example is if you attempt to assign a Python keyword to a variable or use a keyword to define a function:

>>>

>>> pass = True
  File "<stdin>", line 1
    pass = True
         ^
SyntaxError: invalid syntax

>>> def pass():
  File "<stdin>", line 1
    def pass():
           ^
SyntaxError: invalid syntax

When you attempt to assign a value to pass, or when you attempt to define a new function called pass, you’ll get a SyntaxError and see the "invalid syntax" message again.

It might be a little harder to solve this type of invalid syntax in Python code because the code looks fine from the outside. If your code looks good, but you’re still getting a SyntaxError, then you might consider checking the variable name or function name you want to use against the keyword list for the version of Python that you’re using.

The list of protected keywords has changed with each new version of Python. For example, in Python 3.6 you could use await as a variable name or function name, but as of Python 3.7, that word has been added to the keyword list. Now, if you try to use await as a variable or function name, this will cause a SyntaxError if your code is for Python 3.7 or later.

Another example of this is print, which differs in Python 2 vs Python 3:

Version print Type Takes A Value
Python 2 keyword no
Python 3 built-in function yes

print is a keyword in Python 2, so you can’t assign a value to it. In Python 3, however, it’s a built-in function that can be assigned values.

You can run the following code to see the list of keywords in whatever version of Python you’re running:

import keyword
print(keyword.kwlist)

keyword also provides the useful keyword.iskeyword(). If you just need a quick way to check the pass variable, then you can use the following one-liner:

>>>

>>> import keyword; keyword.iskeyword('pass')
True

This code will tell you quickly if the identifier that you’re trying to use is a keyword or not.

Missing Parentheses, Brackets, and Quotes

Often, the cause of invalid syntax in Python code is a missed or mismatched closing parenthesis, bracket, or quote. These can be hard to spot in very long lines of nested parentheses or longer multi-line blocks. You can spot mismatched or missing quotes with the help of Python’s tracebacks:

>>>

>>> message = 'don't'
  File "<stdin>", line 1
    message = 'don't'
                   ^
SyntaxError: invalid syntax

Here, the traceback points to the invalid code where there’s a t' after a closing single quote. To fix this, you can make one of two changes:

  1. Escape the single quote with a backslash ('don't')
  2. Surround the entire string in double-quotes instead ("don't")

Another common mistake is to forget to close string. With both double-quoted and single-quoted strings, the situation and traceback are the same:

>>>

>>> message = "This is an unclosed string
  File "<stdin>", line 1
    message = "This is an unclosed string
                                        ^
SyntaxError: EOL while scanning string literal

This time, the caret in the traceback points right to the problem code. The SyntaxError message, "EOL while scanning string literal", is a little more specific and helpful in determining the problem. This means that the Python interpreter got to the end of a line (EOL) before an open string was closed. To fix this, close the string with a quote that matches the one you used to start it. In this case, that would be a double quote (").

Quotes missing from statements inside an f-string can also lead to invalid syntax in Python:

 1# theofficefacts.py
 2ages = {
 3    'pam': 24,
 4    'jim': 24,
 5    'michael': 43
 6}
 7print(f'Michael is {ages["michael]} years old.')

Here, the reference to the ages dictionary inside the printed f-string is missing the closing double quote from the key reference. The resulting traceback is as follows:

$ python theofficefacts.py
  File "theofficefacts.py", line 7
    print(f'Michael is {ages["michael]} years old.')
         ^
SyntaxError: f-string: unterminated string

Python identifies the problem and tells you that it exists inside the f-string. The message "unterminated string" also indicates what the problem is. The caret in this case only points to the beginning of the f-string.

This might not be as helpful as when the caret points to the problem area of the f-string, but it does narrow down where you need to look. There’s an unterminated string somewhere inside that f-string. You just have to find out where. To fix this problem, make sure that all internal f-string quotes and brackets are present.

The situation is mostly the same for missing parentheses and brackets. If you leave out the closing square bracket from a list, for example, then Python will spot that and point it out. There are a few variations of this, however. The first is to leave the closing bracket off of the list:

# missing.py
def foo():
    return [1, 2, 3

print(foo())

When you run this code, you’ll be told that there’s a problem with the call to print():

$ python missing.py
  File "missing.py", line 5
    print(foo())
        ^
SyntaxError: invalid syntax

What’s happening here is that Python thinks the list contains three elements: 1, 2, and 3 print(foo()). Python uses whitespace to group things logically, and because there’s no comma or bracket separating 3 from print(foo()), Python lumps them together as the third element of the list.

Another variation is to add a trailing comma after the last element in the list while still leaving off the closing square bracket:

# missing.py
def foo():
    return [1, 2, 3,

print(foo())

Now you get a different traceback:

$ python missing.py
  File "missing.py", line 6

                ^
SyntaxError: unexpected EOF while parsing

In the previous example, 3 and print(foo()) were lumped together as one element, but here you see a comma separating the two. Now, the call to print(foo()) gets added as the fourth element of the list, and Python reaches the end of the file without the closing bracket. The traceback tells you that Python got to the end of the file (EOF), but it was expecting something else.

In this example, Python was expecting a closing bracket (]), but the repeated line and caret are not very helpful. Missing parentheses and brackets are tough for Python to identify. Sometimes the only thing you can do is start from the caret and move backward until you can identify what’s missing or wrong.

Mistaking Dictionary Syntax

You saw earlier that you could get a SyntaxError if you leave the comma off of a dictionary element. Another form of invalid syntax with Python dictionaries is the use of the equals sign (=) to separate keys and values, instead of the colon:

>>>

>>> ages = {'pam'=24}
  File "<stdin>", line 1
    ages = {'pam'=24}
                 ^
SyntaxError: invalid syntax

Once again, this error message is not very helpful. The repeated line and caret, however, are very helpful! They’re pointing right to the problem character.

This type of issue is common if you confuse Python syntax with that of other programming languages. You’ll also see this if you confuse the act of defining a dictionary with a dict() call. To fix this, you could replace the equals sign with a colon. You can also switch to using dict():

>>>

>>> ages = dict(pam=24)
>>> ages
{'pam': 24}

You can use dict() to define the dictionary if that syntax is more helpful.

Using the Wrong Indentation

There are two sub-classes of SyntaxError that deal with indentation issues specifically:

  1. IndentationError
  2. TabError

While other programming languages use curly braces to denote blocks of code, Python uses whitespace. That means that Python expects the whitespace in your code to behave predictably. It will raise an IndentationError if there’s a line in a code block that has the wrong number of spaces:

 1# indentation.py
 2def foo():
 3    for i in range(10):
 4        print(i)
 5  print('done')
 6
 7foo()

This might be tough to see, but line 5 is only indented 2 spaces. It should be in line with the for loop statement, which is 4 spaces over. Thankfully, Python can spot this easily and will quickly tell you what the issue is.

There’s also a bit of ambiguity here, though. Is the print('done') line intended to be after the for loop or inside the for loop block? When you run the above code, you’ll see the following error:

$ python indentation.py
  File "indentation.py", line 5
    print('done')
                ^
IndentationError: unindent does not match any outer indentation level

Even though the traceback looks a lot like the SyntaxError traceback, it’s actually an IndentationError. The error message is also very helpful. It tells you that the indentation level of the line doesn’t match any other indentation level. In other words, print('done') is indented 2 spaces, but Python can’t find any other line of code that matches this level of indentation. You can fix this quickly by making sure the code lines up with the expected indentation level.

The other type of SyntaxError is the TabError, which you’ll see whenever there’s a line that contains either tabs or spaces for its indentation, while the rest of the file contains the other. This might go hidden until Python points it out to you!

If your tab size is the same width as the number of spaces in each indentation level, then it might look like all the lines are at the same level. However, if one line is indented using spaces and the other is indented with tabs, then Python will point this out as a problem:

 1# indentation.py
 2def foo():
 3    for i in range(10):
 4        print(i)
 5    print('done')
 6
 7foo()

Here, line 5 is indented with a tab instead of 4 spaces. This code block could look perfectly fine to you, or it could look completely wrong, depending on your system settings.

Python, however, will notice the issue immediately. But before you run the code to see what Python will tell you is wrong, it might be helpful for you to see an example of what the code looks like under different tab width settings:

$ tabs 4 # Sets the shell tab width to 4 spaces
$ cat -n indentation.py
     1   # indentation.py
     2   def foo():
     3       for i in range(10)
     4           print(i)
     5       print('done')
     6   
     7   foo()

$ tabs 8 # Sets the shell tab width to 8 spaces (standard)
$ cat -n indentation.py
     1   # indentation.py
     2   def foo():
     3       for i in range(10)
     4           print(i)
     5           print('done')
     6   
     7   foo()

$ tabs 3 # Sets the shell tab width to 3 spaces
$ cat -n indentation.py
     1   # indentation.py
     2   def foo():
     3       for i in range(10)
     4           print(i)
     5      print('done')
     6   
     7   foo()

Notice the difference in display between the three examples above. Most of the code uses 4 spaces for each indentation level, but line 5 uses a single tab in all three examples. The width of the tab changes, based on the tab width setting:

  • If the tab width is 4, then the print statement will look like it’s outside the for loop. The console will print 'done' at the end of the loop.
  • If the tab width is 8, which is standard for a lot of systems, then the print statement will look like it’s inside the for loop. The console will print 'done' after each number.
  • If the tab width is 3, then the print statement looks out of place. In this case, line 5 doesn’t match up with any indentation level.

When you run the code, you’ll get the following error and traceback:

$ python indentation.py
  File "indentation.py", line 5
    print('done')
                ^
TabError: inconsistent use of tabs and spaces in indentation

Notice the TabError instead of the usual SyntaxError. Python points out the problem line and gives you a helpful error message. It tells you clearly that there’s a mixture of tabs and spaces used for indentation in the same file.

The solution to this is to make all lines in the same Python code file use either tabs or spaces, but not both. For the code blocks above, the fix would be to remove the tab and replace it with 4 spaces, which will print 'done' after the for loop has finished.

Defining and Calling Functions

You might run into invalid syntax in Python when you’re defining or calling functions. For example, you’ll see a SyntaxError if you use a semicolon instead of a colon at the end of a function definition:

>>>

>>> def fun();
  File "<stdin>", line 1
    def fun();
             ^
SyntaxError: invalid syntax

The traceback here is very helpful, with the caret pointing right to the problem character. You can clear up this invalid syntax in Python by switching out the semicolon for a colon.

In addition, keyword arguments in both function definitions and function calls need to be in the right order. Keyword arguments always come after positional arguments. Failure to use this ordering will lead to a SyntaxError:

>>>

>>> def fun(a, b):
...     print(a, b)
...
>>> fun(a=1, 2)
  File "<stdin>", line 1
SyntaxError: positional argument follows keyword argument

Here, once again, the error message is very helpful in telling you exactly what is wrong with the line.

Changing Python Versions

Sometimes, code that works perfectly fine in one version of Python breaks in a newer version. This is due to official changes in language syntax. The most well-known example of this is the print statement, which went from a keyword in Python 2 to a built-in function in Python 3:

>>>

>>> # Valid Python 2 syntax that fails in Python 3
>>> print 'hello'
  File "<stdin>", line 1
    print 'hello'
                ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print('hello')?

This is one of the examples where the error message provided with the SyntaxError shines! Not only does it tell you that you’re missing parenthesis in the print call, but it also provides the correct code to help you fix the statement.

Another problem you might encounter is when you’re reading or learning about syntax that’s valid syntax in a newer version of Python, but isn’t valid in the version you’re writing in. An example of this is the f-string syntax, which doesn’t exist in Python versions before 3.6:

>>>

>>> # Any version of python before 3.6 including 2.7
>>> w ='world'
>>> print(f'hello, {w}')
  File "<stdin>", line 1
    print(f'hello, {w}')
                      ^
SyntaxError: invalid syntax

In versions of Python before 3.6, the interpreter doesn’t know anything about the f-string syntax and will just provide a generic "invalid syntax" message. The problem, in this case, is that the code looks perfectly fine, but it was run with an older version of Python. When in doubt, double-check which version of Python you’re running!

Python syntax is continuing to evolve, and there are some cool new features introduced in Python 3.8:

  • Walrus operator (assignment expressions)
  • F-string syntax for debugging
  • Positional-only arguments

If you want to try out some of these new features, then you need to make sure you’re working in a Python 3.8 environment. Otherwise, you’ll get a SyntaxError.

Python 3.8 also provides the new SyntaxWarning. You’ll see this warning in situations where the syntax is valid but still looks suspicious. An example of this would be if you were missing a comma between two tuples in a list. This would be valid syntax in Python versions before 3.8, but the code would raise a TypeError because a tuple is not callable:

>>>

>>> [(1,2)(2,3)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

This TypeError means that you can’t call a tuple like a function, which is what the Python interpreter thinks you’re doing.

In Python 3.8, this code still raises the TypeError, but now you’ll also see a SyntaxWarning that indicates how you can go about fixing the problem:

>>>

>>> [(1,2)(2,3)]
<stdin>:1: SyntaxWarning: 'tuple' object is not callable; perhaps you missed a comma?
Traceback (most recent call last):   
  File "<stdin>", line 1, in <module>    
TypeError: 'tuple' object is not callable

The helpful message accompanying the new SyntaxWarning even provides a hint ("perhaps you missed a comma?") to point you in the right direction!

Conclusion

In this tutorial, you’ve seen what information the SyntaxError traceback gives you. You’ve also seen many common examples of invalid syntax in Python and what the solutions are to those problems. Not only will this speed up your workflow, but it will also make you a more helpful code reviewer!

When you’re writing code, try to use an IDE that understands Python syntax and provides feedback. If you put many of the invalid Python code examples from this tutorial into a good IDE, then they should highlight the problem lines before you even get to execute your code.

Getting a SyntaxError while you’re learning Python can be frustrating, but now you know how to understand traceback messages and what forms of invalid syntax in Python you might come up against. The next time you get a SyntaxError, you’ll be better equipped to fix the problem quickly!

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Identify Invalid Python Syntax

Did you know that even the most experienced programmers make errors in their programs?

However, one of the things that separates them from novices is that they know how to fix an error. Not knowing how to fix an error will not only waste a lot of time, but even worse, it can demotivate you to the point where you feel dumb and give up learning how to program. In this reading, you will learn the secrets of finding and fixing a Python code error.

I like examples, so let’s take a look at one. The Python code below is supposed to create a dictionary and print that dictionary out.

data = ("Name":"John", "Surname":"Smith")
print(data)

However, when executed, the code produces the following output:

File "script2.py", line 1
data = ("Name":"John", "Surname":"Smith")
              ^
SyntaxError: invalid syntax

That’s the entire error message you got. Now here are the steps on how to understand and solve that error:

  1. Read the error from the beginning. The first line tells you the location of the error. So, the error happened in script1.py (that was the name of my script), on line 1. Now you know where the error occurred. For your convenience, you also have the line that caused the error printed out in the second line of the error message.
  2. Next, look at the error type. In this case, the error type is a SyntaxError. That means you have written something that doesn’t follow the Python syntax rules. So, now you have an idea of what error you are dealing with. For an overview of possible Python error types, you can look here.
  3. Look at the details of the error. On the right of SyntaxError you have the detailed information about the error. In this case, this information is «invalid syntax»and you also have an arrow character pointing upward. That error is pointing to the colon character. The arrow is trying to say that the colon doesn’t belong there.
  4. Time to use your logic. Now, the Python interpreter gave you all the information that a robot can give. Now it’s your turn as a human to use your logic to fix the error. So, Python executes a script from top to bottom, line by line, and reads each line from left to right. In this case, it started to read the first line, and it detected round brackets after the assignment operator. That means you are creating a tuple. That’s fine. But then after you write the first item (“Name” in this case). You were supposed to write a comma to separate that item from the next item, but you used a colon instead, so the interpreter is saying that a colon is not syntactically correct to use with round brackets.

Therefore, you should make up your mind to either write a tuple like:

 data = ("Name", "John", "Surname", "Smith")

Or a dictionary of key-value pairs, like:

 data = {"Name":"John", "Surname":"Smith".  

The decision is up to you. In this case, though, I believe the programmer meant to write a dictionary, so I am going to replace the round brackets with curly brackets because I know a dictionary is defined through curly brackets.

That’s the formula to fix an error. Sometimes though errors are much more complex than this, so in that case copying and pasting the last line of the error (SyntaxError: invalid syntax in this case ) on Google will usually show up forums posts with answers on fixing that particular error. However, that should be the last resort, as it’s better to use your knowledge first.

Next Lecture

If something is wrong with your code, Python will try to help you by displaying an error message. These error messages are just bugs in your code. In this article, I’ll walk you through how to fix bugs in Python.

The bugs might seem a little confusing at first, but they’ll give you clues as to why your program isn’t working and how to fix it. Python displays error messages in a red coloured text in the shell window. The program stops working when an error message appears. That message tells you which line of code caused the error.

Also, Read – 100+ Machine Learning Projects Solved and Explained.

When an error message appears in the shell, right-click on it and choose “Go to File / Line” from the drop-down menu. The IDLE editor jumps directly to this line of code so that you can start debugging.

Types of Errors in Python

Types of Errors in Python

Before we look at how to fix bugs in Python, let’s take a quick look at the types of bugs in Python. There are mainly 5 types of bugs in Python:

  1. Syntax errors: When you receive a syntax error message, it indicates that you typed something wrong.
  2. Indentation errors: Python uses indentation to understand where blocks of code start and end. An indentation error means that something is wrong with the way you have structured the code.
  3. Type errors: A type error is not a typing error. This means that your code has mixed one data type with another, for example mistaking numbers for strings.
  4. Name errors: A name error message appears if your code uses the name of a variable or function that has not yet been created.
  5. Logic errors: Sometimes you can tell something is wrong even though Python hasn’t given you an error message because your program isn’t doing what you expected. You may have a logic error.

How To Fix Bugs in Python?

Sometimes you might think that you can never make a program work, but don’t give up. If you follow all of the tips mentioned below, you will be able to identify and fix most bugs in Python:

  1. If you are creating projects that are already common among the coding community, try searching the internet for it using error as a keyword. You will have a good idea.
  2. Check if everything is spelt correctly.
  3. Check if you have any unnecessary spaces at the start of a line.
  4. Check to see if you’ve been confused with numbers for letters, such as 0 and O.
  5. Check if you’ve used upper and lower case letters in the correct places.
  6. Check if all open parentheses have a corresponding closing parenthesis.
  7. Check if all single and double quotes have a matching closing quote.
  8. Ask for help on platforms like Stackoverflow, you can even ask us in the comments section below.
  9. Always make sure to save your code after making any changes.

I hope you liked this article on how to fix bugs in the Python programming language. Feel free to ask your valuable questions in the comments section below.

Aman Kharwal

I’m a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1372

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 Read: How to Fix Unexpected EOF While Parsing Error In Python

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

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 Read: How 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 Read: 10 Best Programming Apps To Learn Python

Error Fix Code

print("CodeITBro")

Output

CodeITBro

Also Read: Python 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 Read: Python 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 Read: Python 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 Read: Increment 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 Read: Python 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 Read: How To Concatenate Arrays in Python [With Examples]

Error Fix Code

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

Output

Even

Also Read: What 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 Read: How 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 Read: What 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 Read: How 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 Read: How 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 Read: Arithmetic 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.

SyntaxError — это ошибка, которая легко может ввести в ступор начинающего программиста. Стоит забыть одну запятую или не там поставить кавычку и Python наотрез откажется запускать программу. Что ещё хуже, по выводу в консоль сложно сообразить в чём дело. Выглядят сообщения страшно и непонятно. Что с этим делать — не ясно. Вот неполный список того, что можно встретить:

  • SyntaxError: invalid syntax
  • SyntaxError: EOL while scanning string literal
  • SyntaxError: unexpected EOF while parsing

Эта статья о том, как справиться с синтаксической ошибкой SyntaxError. Дочитайте её до конца и получите безотказный простой алгоритм действий, что поможет вам в трудную минуту — ваш спасательный круг.

Работать будем с программой, которая выводит на экран список учеников. Её код выглядит немного громоздко и, возможно, непривычно. Если не всё написанное вам понятно, то не отчаивайтесь, чтению статьи это не помешает.


students = [
    ['Егор', 'Кузьмин'],
    ['Денис', 'Давыдов'],
]

for first_name, last_name in students:
    label = 'Имя ученика: {first_name} {last_name}'.format(
        first_name = first_name
        last_name = last_name
    )

    print(label)

Ожидается примерно такой результат в консоли:

$ python script.py
Имя ученика: Егор Кузьмин
Имя ученика: Денис Давыдов

Но запуск программы приводит к совсем другому результату. Скрипт сломан:

$ python script.py
  File "script.py", line 9
    last_name = last_name
            ^
SyntaxError: invalid syntax

Ошибки в программе бывают разные и каждой нужен свой особый подход. Первым делом внимательно посмотрите на вывод программы в консоль. На последней строчке написано SyntaxError: invalid syntax. Если эти слова вам не знакомы, то обратитесь за переводом к Яндекс.Переводчику:

SyntaxError: недопустимый синтаксис
SyntaxError: неверный синтаксис

Первое слово SyntaxError Яндекс не понял. Помогите ему и разделите слова пробелом:

Syntax Error: invalid syntax
Синтаксическая ошибка: неверный синтаксис

Теория. Синтаксические ошибки

Программирование — это не магия, а Python — не волшебный шар. Он не умеет предсказывать будущее, у него нет доступа к секретным знаниями, это просто автомат, это программа. Узнайте как она работает, как ищет ошибки в коде, и тогда легко найдете эффективный способ отладки. Вся необходимая теория собрана в этом разделе, дочитайте до конца.

SyntaxError — это синтаксическая ошибка. Она случается очень рано, еще до того, как Python запустит программу. Вот что делает компьютер, когда вы запускаете скрипт командой python script.py:

  1. запускает программу python
  2. python считывает текст из файла script.py
  3. python превращает текст программы в инструкции
  4. python исполняет инструкции

Синтаксическая ошибка SyntaxError возникает на четвёртом этапе в момент, когда Python разбирает текст программы на понятные ему компоненты. Сложные выражения в коде он разбирает на простейшие инструкции. Вот пример кода и инструкции для него:

person = {'name': 'Евгений'}

Инструкции:

  1. создать строку 'Евгений'
  2. создать словарь
  3. в словарь добавить ключ 'name' со значением 'Евгений'
  4. присвоить результат переменной person

SyntaxError случается когда Python не смог разбить сложный код на простые инструкции. Зная это, вы можете вручную разбить код на инструкции, чтобы затем проверить каждую из них по отдельности. Ошибка прячется в одной из инструкций.

1. Найдите поломанное выражение

Этот шаг сэкономит вам кучу сил. Найдите в программе сломанный участок кода. Его вам предстоит разобрать на отдельные инструкции. Посмотрите на вывод программы в консоль:

$ python script.py
  File "script.py", line 9
    last_name = last_name
            ^
SyntaxError: invalid syntax

Вторая строчка сообщает: File "script.py", line 9 — ошибка в файле script.py на девятой строчке. Но эта строка является частью более сложного выражения, посмотрите на него целиком:

label = 'Имя ученика: {first_name} {last_name}'.format(
    first_name = first_name
    last_name = last_name
)

2. Разбейте выражение на инструкции

В прошлых шагах вы узнали что сломан этот фрагмент кода:

label = 'Имя ученика: {first_name} {last_name}'.format(
    first_name = first_name
    last_name = last_name
)

Разберите его на инструкции:

  1. создать строку 'Имя ученика: {first_name} {last_name}'
  2. получить у строки метод format
  3. вызвать функцию с двумя аргументами
  4. результат присвоить переменной label

Так выделил бы инструкции программист, но вот Python сделать так не смог и сломался. Пора выяснить на какой инструкции нашла коса на камень.

Теперь ваша задача переписать код так, чтобы в каждой строке программы исполнялось не более одной инструкции из списка выше. Так вы сможете тестировать их по отдельности и облегчите себе задачу. Так выглядит отделение инструкции по созданию строки:

# 1. создать строку
template = 'Имя ученика: {first_name} {last_name}'

label = template.format(
    first_name = first_name
    last_name = last_name
)

Сразу запустите код, проверьте что ошибка осталась на прежнему месте. Приступайте ко второй инструкции:

# 1. создать строку
template = 'Имя ученика: {first_name} {last_name}'

# 2. получить у строки метод
format = template.format

label = format(
    first_name = first_name
    last_name = last_name
)

Строка format = template.format создает новую переменную format и кладёт в неё функцию. Да, да, это не ошибка! Python разрешает класть в переменные всё что угодно, в том числе и функции. Новая переменная переменная format теперь работает как обычная функция, и её можно вызвать: format(...).

Снова запустите код. Ошибка появится внутри format. Под сомнением остались две инструкции:

  1. вызвать функцию с двумя аргументами
  2. результат присвоить переменной label

Скорее всего, Python не распознал вызов функции. Проверьте это, избавьтесь от последней инструкции — от создания переменной label:

# 1. создать строку
template = 'Имя ученика: {first_name} {last_name}'

# 2. получить у строки метод
format = template.format

# 3. вызвать функцию
format(
    first_name = first_name
    last_name = last_name
)

Запустите код. Ошибка снова там же — внутри format. Выходит, код вызова функции написан с ошибкой, Python не смог его превратить в инструкцию.

3. Проверьте синтаксис вызова функции

Теперь вы знаете что проблема в коде, вызывающем функцию. Можно помедитировать еще немного над кодом программы, пройтись по нему зорким взглядом еще разок в надежде на лучшее. А можно поискать в сети примеры кода для сравнения.

Запросите у Яндекса статьи по фразе “Python синтаксис функции”, а в них поищите код, похожий на вызов format и сравните. Вот одна из первых статей в поисковой выдаче:

  • Функции в Python

Уверен, теперь вы нашли ошибку. Победа!

Понравилась статья? Поделить с друзьями:
  • Python error code 2502
  • Pycharm как изменить цвет кода
  • Python error address already in use
  • Pycharm как изменить тип файла
  • Python error 193