Solve the Unexpected EOF while parsing syntax error in Python

In this short tutorial we’ll learn how to troubleshoot the the Unexpected EOF while parsing error that we might encounter from time to time in our Python programs. The meaning of this error is that the Python interpreter runs through the end of your Python file but can’t find the end of an open code block. Here are two prevalent cases in which that happens:

  1. We forgot to close a parenthesis – for example in a print or an input statement.
  2. We forgot to add a complete block to our code, for example when using a try statement, we didn’t include an except clause.

Unexpected EOF errror message

The typical error message we will get is:

SyntaxError: unexpected EOF while parsing

Troubleshooting the error message

Example 1: missing parenthesis

As indicated below, one of the key root causes for the error is failing to close a simple parenthesis, for example:

# a closing parenthesis is missing 
print('Python is my favorite language'

This can be easily fixed:

# adding the closing parenthesis does the trick
print('Python is my favorite language')

Example 2 – try block with no except or finally clause

Consider the following example:

lang_lst =['Python', 'R', 'Go', 'Haskell']

try:
    for lang in lang_lst:
        if lang == 'Python':
            print('That is my favorite language')

This will render the EOF syntax error as the try block wasn’t properly closed. We can easily solve this by adding an except of a finally clause:

try:
    for lang in lang_lst:
        if lang == 'Python':
            print('That is my favorite language')

# adding an except of a finally clause does the trick
finally:
    print('The program is completed')

Additional Learning

How to divide a Python list without using the split string method?