syntaxerror: unexpected eof while parsing Python – Code Example


Python throws syntaxerror: unexpected eof while parsing, when there is –

  • extra open parenthesis,
  • extra quote in strings,
  • missed parenthesis,
  • try block without finally,
  • loops or conditions without body.

In this article we will check out all the cases we listed here.

Solutions & Code Examples

Let’s see the solutions for common reasons of this error.

Extra parenthesis

We can get eof while parsing error when there is extra parenthesis in our syntax. Look at this code –

print(('This has too many parenthesis')

This code will throw the error because the parenthesis could not be traversed correctly. We have 2 open parenthesis but 1 closed. That’s why Python throws EOF error. Output –

SyntaxError: unexpected EOF while parsing

Extra quote in strings

If you write your programs on text editors like notepad, then there is no linter which can warn you for syntax errors, like in IDEs. Mismatching quotes in strings is one of the reason for error. Check this code –

wrongString = 'This has unbalanced quotes''

Here we will get a slightly different error – SyntaxError: EOL while scanning string literal. This is EOL error. You can see that we have used unbalanced quotes. Total 3 quotes in 1 string. Output –

SyntaxError: EOL while scanning string literal

No closing parenthesis

Similar to extra parenthesis, if you forget to close the parenthesis you will get unexpected EOF error. Check the code –

print('Forgot to close parenthesis'

Here in our print statement we have no closing parenthesis ) and that’s why we got error. Output –

SyntaxError: unexpected EOF while parsing

Try block without finally or except

This is one of the mistake which could be overlooked easily. If you use a try block without using finally or except then python will throw EOF error.

    print('Try block without finally')

Output –

SyntaxError: unexpected EOF while parsing

To correctly run this code, we will need to add finally block –

    print('Try block')
    print('with finally')

Loops & conditions without body

What will happen if you write a loop but there is no body in it? It will throw error but which one? By running this code, you will get the answer –

for i in [2,3,4]:

Output –

SyntaxError: unexpected EOF while parsing

You can see that it will throw syntaxerror: unexpected EOF while parsing. The same will happen in case of bodyless conditions too.

    Tweet this to help others

Live Demo

Open Live Demo