syntaxerror: unexpected eof while parsing – Python


Python throws syntaxerror: unexpected eof while parsing, in cases like extra open parenthesis, extra quote in strings, missed parenthesis, try block without finally, and loops or conditions without body. In this article we will check out all the cases we listed here.

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')

SyntaxError: unexpected EOF while parsing

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.

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 error, like in IDEs. Mismatching quotes in strings is one of the reason for error. Check this code –

>>> wrongString = 'This has unbalanced quotes''

SyntaxError: EOL while scanning string literal

Here we will get a slightly different error. This is EOL error. You can see that we have used unbalanced quotes. Total 3 quotes in 1 string.

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'

SyntaxError: unexpected EOF while parsing

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

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.

>>> try:
...    print('Try block without finally')

SyntaxError: unexpected EOF while parsing

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

>>> try:
...    print('Try block')
... finally:
...    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]:

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

Demo might not work in private window (incognito)

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like