В Python простой, но строгий синтаксис. Если забыть закрыть блок кода, то возникнет ошибка «SyntaxError: unexpected EOF while parsing». Это происходит часто, например, когда вы забыли добавить как минимум одну строку в цикл for.
В этом материале разберемся с этой ошибкой, и по каким еще причинам она возникает. Разберем несколько примеров, чтобы понять, как с ней справляться.
Ошибка «SyntaxError: unexpected EOF while parsing» возникает в том случае, когда программа добирается до конца файла, но не весь код еще выполнен. Это может быть вызвано ошибкой в структуре или синтаксисе кода.
EOF значит End of File. Представляет собой последний символ в Python-программе.
Python достигает конца файла до выполнения всех блоков в таких случаях:
- Если забыть заключить код в специальную инструкцию, такую как, циклы for или while, или функцию.
- Не закрыть все скобки на строке.
Разберем эти ошибки на примерах построчно.
Пример №1: незавершенные блоки кода
Циклы for и while, инструкции if и функции требуют как минимум одной строки кода в теле. Если их не добавить, результатом будет ошибка EOF.
Рассмотрим такой пример цикла for, который выводит все элементы рецепта:
ingredients = ["325г муки", "200г охлажденного сливочного масла", "125г сахара", "2 ч. л. ванили", "2 яичных желтка"]
for i in ingredients:
Определяем переменную ingredients
, которая хранит список ингредиентов для ванильного песочного печенья. Используем цикл for для перебора по каждому из элементов в списке. Запустим код и посмотрим, что произойдет:
File "main.py", line 4
^
SyntaxError: unexpected EOF while parsing
Внутри цикла for нет кода, что приводит к ошибке. То же самое произойдет, если не заполнить цикл while, инструкцию if или функцию.
Для решения проблемы требуется добавить хотя бы какой-нибудь код. Это может быть, например, инструкция print()
для вывода отдельных ингредиентов в консоль:
for i in ingredients:
print(i)
Запустим код:
325г муки
200г охлажденного сливочного масла
125г сахара
2 ч. л. ванили
2 яичных желтка
Код выводит каждый ингредиент из списка, что говорит о том, что он выполнен успешно.
Если же кода для такого блока у вас нет, используйте оператор pass
как заполнитель. Выглядит это вот так:
for i in ingredients:
pass
Такой код ничего не возвращает. Инструкция pass
говорит о том, что ничего делать не нужно. Такое ключевое слово используется в процессе разработке, когда разработчики намечают будущую структуру программы. Позже pass заменяются на реальный код.
Пример №2: незакрытые скобки
Ошибка «SyntaxError: unexpected EOF while parsing» также возникает, если не закрыть скобки в конце строки с кодом.
Напишем программу, которая выводит информацию о рецепте в консоль. Для начала определим несколько переменных:
name = "Капитанская дочка"
author = "Александр Пушкин"
genre = "роман"
Отформатируем строку с помощью метода .format()
:
print('Книга "{}" - это {}, автор {}'.format(name, genre, author)
Значения {}
заменяются на реальные из .format()
. Это значит, что строка будет выглядеть вот так:
Книга "НАЗВАНИЕ" - это ЖАНР, автор АВТОР
Запустим код:
File "main.py", line 7
^
SyntaxError: unexpected EOF while parsing
На строке кода с функцией print()
мы закрываем только один набор скобок, хотя открытыми были двое. В этом и причина ошибки.
Решаем проблему, добавляя вторую закрывающую скобку («)») в конце строки с print()
.
print('Книга "{}" - это {}, автор {}'.format(name, genre, author))
Теперь на этой строке закрываются две скобки. И все из них теперь закрыты. Попробуем запустить код снова:
Книга "Капитанская дочка" это роман. Александр Пушкин
Теперь он работает. То же самое произойдет, если забыть закрыть скобки словаря {}
или списка []
.
Выводы
Ошибка «SyntaxError: unexpected EOF while parsing» возникает, если интерпретатор Python добирается до конца программы до выполнения всех строк.
Для решения этой проблемы сперва нужно убедиться, что все инструкции, включая while, for, if и функции содержат код. Также нужно проверить, закрыты ли все скобки.
Table of Contents
Hide
- What is an unexpected EOF while parsing error in Python?
- How to fix SyntaxError: unexpected EOF while parsing?
- Scenario 1 – Missing parenthesis or Unclosed parenthesis
- Scenario 2: Incomplete functions along with statements, loops, try and except
- Conclusion
The SyntaxError: unexpected EOF while parsing occurs if the Python interpreter reaches the end of your source code before executing all the code blocks. This happens if you forget to close the parenthesis or if you have forgotten to add the code in the blocks statements such as for
, if
, while
, etc. To solve this error check if all the parenthesis are closed properly and you have at least one line of code written after the statements such as for
, if
, while
, and functions.
What is an unexpected EOF while parsing error in Python?
EOF stands for End of File and SyntaxError: unexpected EOF while parsing error occurs where the control in the code reaches the end before all the code is executed.
Generally, if you forget to complete a code block in python code, you will get an error “SyntaxError: unexpected EOF while parsing.”
Most programming languages like C, C++, and Java use curly braces { }
to define a block of code. Python, on the other hand, is a “block-structured language” that uses indentation.
A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition. Each command typed interactively is a block.
There are several reasons why we get this error while writing the python code. Let us look into each of the scenarios and solve the issue.
Sometimes if the code is not indented properly you will get unindent does not match any outer indentation error.
Scenario 1 – Missing parenthesis or Unclosed parenthesis
One of the most common scenarios is an unclosed parenthesis (), brackets [], and curly braces {} in the Python code.
- Parenthesis is mainly used in print statements, declaring tuples, calling the built-in or user-defined methods, etc.
- Square brackets are used in declaring the Arrays, Lists, etc in Python
- Curly braces are mainly used in creating the dictionary and JSON objects.
In the below example, we have taken simple use cases to demonstrate the issue. In larger applications, the code will be more complex and we should use IDEs such as VS Code, and PyCharm which detect and highlights these common issues to developers.
# Paranthesis is not closed properly in the Print Statement
print("Hello"
# Square bracket is not closed while declaring the list
items =[1,2,3,4,5
# Curly Braces is not closed while creating the dictionary
dictionary={ 'FirstName':'Jack'
Output
SyntaxError: unexpected EOF while parsing
If you look at the above code, we have a print statement where the parenthesis has not closed, a list where the square bracket is not closed, and a dictionary where the curly braces are not closed. Python interpreter will raise unexpected EOF while parsing.
Solution :
We can fix the issue by enclosing the braces, parenthesis, and square brackets properly in the code as shown below.
# Paranthesis is now closed properly in the Print Statement
print("Hello")
# Square bracket is now closed while declaring the list
items =[1,2,3,4,5]
print(items)
# Curly Braces is now closed while creating the dictionary
dictionary={ 'FirstName':'Jack'}
print(dictionary)
Output
Hello
[1, 2, 3, 4, 5]
{'FirstName': 'Jack'}
If we try to execute the program notice the error is gone and we will get the output as expected.
Scenario 2: Incomplete functions along with statements, loops, try and except
The other scenario is if you have forgotten to add the code after the Python statements, loops, and methods.
- if Statement / if else Statement
- try-except statement
- for loop
- while loop
- user-defined function
Python expects at least one line of code to be present right after these statements and loops. If you have forgotten or missed to add code inside these code blocks Python will raise SyntaxError: unexpected EOF while parsing
Let us look at some of these examples to demonstrate the issue. For demonstration, all the code blocks are added as a single code snippet.
# Code is missing after the for loop
fruits = ["apple","orange","grapes","pineapple"]
for i in fruits :
# Code is missing after the if statement
a=5
if (a>10):
# Code is missing after the else statement
a=15
if (a>10):
print("Number is greater than 10")
else:
# Code is missing after the while loop
num=15
while(num<20):
# Code is missing after the method declaration
def add(a,b):
Output
SyntaxError: unexpected EOF while parsing
Solution :
We can fix the issue by addressing all the issues in each code block as mentioned below.
- for loop: We have added the print statement after the for loop.
- if else statement: After the conditional check we have added the print statement which fixes the issue.
- while loop: We have added a print statement and also incremented the counter until the loop satisfies the condition.
- method: The method definition cannot be empty we have added the print statement to fix the issue.
# For loop fixed
fruits = ["apple", "orange", "grapes", "pineapple"]
for i in fruits:
print(i)
# if statement fixed
a = 5
if a > 10:
print("number is greated than 10")
else:
print("number is lesser than 10")
# if else statement fixed
a = 15
if a > 10:
print("Number is greater than 10")
else:
print("number is lesser than 10")
# while loop fixed
num = 15
while num < 20:
print("Current Number is", num)
num = num + 1
# Method fix
def add(a, b):
print("Hello Python")
add(4, 5)
Output
apple
orange
grapes
pineapple
number is lesser than 10
Number is greater than 10
Current Number is 15
Current Number is 16
Current Number is 17
Current Number is 18
Current Number is 19
Hello Python
Conclusion
The SyntaxError: unexpected EOF while parsing
occurs if the Python interpreter reaches the end of your source code before executing all the code blocks. To resolve the SyntaxError: unexpected EOF while parsing in Python, make sure that you follow the below steps.
- Check for Proper Indentation in the code.
- Make sure all the parenthesis, brackets, and curly braces are opened and closed correctly.
- At least one statement of code exists in loops, statements, and functions.
- Verify the syntax, parameters, and the closing statements
In this tutorial, you will learn how fix unexpected EOF while parsing error in Python. Unexpected EOF while parsing error is a Syntax error and occurs when the interpreter reaches the end of the python code before any code block is complete. This error occurs when the body is not coded/included inside conditional statements (if, else), loops (for, while), functions, etc.
Below are the cases when the “Unexpected EOF While Parsing Error” occurs and also provided the ways to fix those errors.
Also Read: How To Copy List in Python
1. Fix – Unexpected EOF while parsing error when using conditional statements
Unexpected EOF while parsing error occurs in conditional statements when any if, else statement is used without a single line of the body.
Example 1: Let’s look into the sample code which throws the Unexpected EOF error while using the if statement.
Code:
number = 1 if(number==1):
Error:
File "<ipython-input-2-8cb60fd8f815>", line 2 if(number==1): ^ SyntaxError: unexpected EOF while parsing
Also Read: 10 Best Programming Apps To Learn Python
2. Fix – Unexpected EOF while parsing error when using loops
Unexpected EOF while parsing error occurs in loops when any for/while statement is used without a single line of body inside them.
Example 1: Let’s look into the sample code that throws the Unexpected EOF error while using the loop.
sum=0 # sum of 1-10 numbers for i in range(1,11): Error File "<ipython-input-7-1f8b5a6d6ae0>", line 3 for i in range(1,11): ^ SyntaxError: unexpected EOF while parsing
The error unexpected EOF while parsing occurred because the for loop didn’t consist of a body/code to execute inside the loop. So to fix this error, we need to add the code block inside the for loop.
Code Fix:
sum=0 # sum of 1-10 numbers for i in range(1,11): sum=sum+i print("Sum of 1-10 numbers = ",sum)
Output:
Sum of 1-10 numbers = 55
Also Read: Python Program To Reverse A Number
Example 2: Let’s look into the sample code which throws the Unexpected EOF error while using a while loop.
Code:
number=1 # print 1 to 10 number while(i<=10):
Error:
File "<ipython-input-10-f825e1f8a55a>", line 3 while(i<=10): ^ SyntaxError: unexpected EOF while parsing
The error unexpected EOF while parsing occurred because the while loop didn’t consist of a body/code to execute. So to fix this error, we need to add the code block inside the while loop.
Also Read: Python Program to Find Sum of Digits [5 Methods]
Code Fix:
number=1 # print 1 to 10 number while(number<=10): print(number,end=" ") number=number+1
Output:
1 2 3 4 5 6 7 8 9 10
Also Read: Python Program To Check If A Number Is a Perfect Square
3. Fix – Unexpected EOF while parsing error in functions
Unexpected EOF while parsing error occurs in function when any function is defined without a body or when we made syntax mistakes while calling the function.
Example 1: Let’s look into the sample code which throws the Unexpected EOF error when we define any function with no body.
Code:
def findEvenorNot(number):
Error:
File "<ipython-input-17-7cb37f6aa589>", line 1 def findEvenorNot(number): ^ SyntaxError: unexpected EOF while parsing
The error unexpected EOF while parsing occurred because the function findEvenorNot is defined without anybody/code. So to fix this error, we need to add the code block inside the function.
Code Fix:
def findEvenorNot(number): if(number%2==0): print(number," is Even") else: print(number," is Odd") findEvenorNot(24)
Output:
24 is Even
Also Read: Increment and Decrement Operators in Python
Example 2: Let’s look into another sample code that throws the Unexpected EOF error when we call a function with incorrect syntax.
Code:
def findEvenorNot(number): if(number%2==0): print(number," is Even") else: print(number," is Odd") findEvenorNot(
Error:
File "<ipython-input-24-35123bc59f61>", line 7 findEvenorNot( ^ SyntaxError: unexpected EOF while parsing
The error unexpected EOF while parsing occurred because the function call had incorrect syntax. So to fix this error, we need to call the function with proper syntax i.e., functionName(parameter1, parameter2, …..).
Also Read: Python Dictionary Length [How To Get Length]
Code Fix:
def findEvenorNot(number): if(number%2==0): print(number," is Even") else: print(number," is Odd") findEvenorNot(831)
Output:
831 is Odd
Also Read: How To Concatenate Arrays in Python [With Examples]
4. Fix – Unexpected EOF while parsing error due to missing parenthesis
Unexpected EOF while parsing error also occurs if we miss any parentheses while using any standard/user-defined functions.
Note: The above example also comes under this category.
Example: Let’s look into an example code that throws the Unexpected EOF error due to missing parenthesis.
Code:
programmingLanguages=["C", "C++","Java","Python","JS"] for lang in programmingLanguages: print(lang
Error:
File "<ipython-input-27-c9c853e4f9e6>", line 4 print(lang ^ SyntaxError: unexpected EOF while parsing
The error unexpected EOF while parsing occurred due to closing parenthesis miss in the print statement. So to fix this error, we need to add the missing parenthesis.
Code Fix:
programmingLanguages=["C", "C++","Java","Python","JS"] for lang in programmingLanguages: print(lang)
Output:
C C++ Java Python JS
Also Read: What Does The Python Percent Sign Mean?
5. Fix – Unexpected EOF while parsing error in Try Except blocks
Unexpected EOF while parsing error also occurs if we didn’t include an except block for a try block.
Example: Let’s look into an example code that throws the Unexpected EOF error due to missing an except block for a try block.
Code:
number = 18 try: result = number/0 print(result)
Error:
File "<ipython-input-2-79e117053f09>", line 5 print(result) ^ SyntaxError: unexpected EOF while parsing
The error unexpected EOF while parsing occurred due to the absence of except block for a try block. So to fix this error, we need to include an except block for the try block.
Code Fix:
number = 18 try: result = number/0 print(result) except: print("Division by zero exception")
Output:
Division by zero exception
Also Read: How to Create an Empty Array In Python
Summary
These are some ways when the “unexpected EOF while parsing” error occurs and ways to fix the errors.
Hello Friends! I am Himanshu, a hobbyist programmer, tech enthusiast, and digital content creator.
With CodeItBro, my mission is to promote coding and help people from non-tech backgrounds to learn this modern-age skill!
I’m getting an error while running this part of the code. I tried some of the existing solutions, but none of them helped.
elec_and_weather = pd.read_csv(r'C:HOUR.csv', parse_dates=True,index_col=0)
# Add historic DEMAND to each X vector
for i in range(0,24):
elec_and_weather[i] = np.zeros(len(elec_and_weather['DEMAND']))
elec_and_weather[i][elec_and_weather.index.hour==i] = 1
# Set number of hours prediction is in advance
n_hours_advance = 24
# Set number of historic hours used
n_hours_window = 24
for k in range(n_hours_advance,n_hours_advance+n_hours_window):
elec_and_weather['DEMAND_t-%i'% k] = np.zeros(len(elec_and_weather['DEMAND']))'
I always get this error:
for i in range(0,24):
File "<ipython-input-29-db3022a769d1>", line 1
for i in range(0,24):
^
SyntaxError: unexpected EOF while parsing
File "<ipython-input-25-df0a44131c36>", line 1
for k in range(n_hours_advance,n_hours_advance+n_hours_window):
^
SyntaxError: unexpected EOF while parsing
Related problem in IDLE or the command-line REPL: Why does input() give a SyntaxError when I just press enter?
Hello Friends! I am Himanshu, a hobbyist programmer, tech enthusiast, and digital content creator.
With CodeItBro, my mission is to promote coding and help people from non-tech backgrounds to learn this modern-age skill!
I’m getting an error while running this part of the code. I tried some of the existing solutions, but none of them helped.
elec_and_weather = pd.read_csv(r'C:HOUR.csv', parse_dates=True,index_col=0)
# Add historic DEMAND to each X vector
for i in range(0,24):
elec_and_weather[i] = np.zeros(len(elec_and_weather['DEMAND']))
elec_and_weather[i][elec_and_weather.index.hour==i] = 1
# Set number of hours prediction is in advance
n_hours_advance = 24
# Set number of historic hours used
n_hours_window = 24
for k in range(n_hours_advance,n_hours_advance+n_hours_window):
elec_and_weather['DEMAND_t-%i'% k] = np.zeros(len(elec_and_weather['DEMAND']))'
I always get this error:
for i in range(0,24):
File "<ipython-input-29-db3022a769d1>", line 1
for i in range(0,24):
^
SyntaxError: unexpected EOF while parsing
File "<ipython-input-25-df0a44131c36>", line 1
for k in range(n_hours_advance,n_hours_advance+n_hours_window):
^
SyntaxError: unexpected EOF while parsing
Related problem in IDLE or the command-line REPL: Why does input() give a SyntaxError when I just press enter?
Karl Knechtel
61.7k11 gold badges98 silver badges148 bronze badges
asked Apr 3, 2017 at 16:02
6
The SyntaxError: unexpected EOF while parsing
means that the end of your source code was reached before all code blocks were completed. A code block starts with a statement like for i in range(100):
and requires at least one line afterwards that contains code that should be in it.
It seems like you were executing your program line by line in the ipython console. This works for single statements like a = 3
but not for code blocks like for loops. See the following example:
In [1]: for i in range(100):
File "<ipython-input-1-ece1e5c2587f>", line 1
for i in range(100):
^
SyntaxError: unexpected EOF while parsing
To avoid this error, you have to enter the whole code block as a single input:
In [2]: for i in range(5):
...: print(i, end=', ')
0, 1, 2, 3, 4,
answered Apr 3, 2017 at 17:41
FelixFelix
6,0914 gold badges24 silver badges44 bronze badges
2
This can simply also mean you are missing or have too many parentheses. For example this has too many, and will result in unexpected EOF
:
print(9, not (a==7 and b==6)
m02ph3u5
2,9456 gold badges37 silver badges50 bronze badges
answered Jul 1, 2019 at 0:37
Mike GMike G
7105 silver badges8 bronze badges
0
My syntax error was semi-hidden in an f-string
print(f'num_flex_rows = {self.}nFlex Rows = {flex_rows}nMax elements = {max_elements}')
should be
print(f'num_flex_rows = {self.num_rows}nFlex Rows = {flex_rows}nMax elements = {max_elements}')
It didn’t have the PyCharm spell-check-red line under the error.
It did give me a clue, yet when I searched on this error message, it of course did not find the error in that bit of code above.
Had I looked more closely at the error message, I would have found the » in the error. Seeing Line 1 was discouraging and thus wasn’t paying close attention Searching for
self.)
yielded nothing. Searching for
self.
yielded practically everything :-
If I can help you avoid even a minute longer of deskchecking your code, then mission accomplished
C:PythonAnaconda3python.exe
C:/Python/PycharmProjects/FlexForms/FlexForm.py File «»,
line 1
(self.)
^ SyntaxError: unexpected EOF while parsingProcess finished with exit code 1
answered Dec 13, 2017 at 0:31
2
Here is one of my mistakes that produced this exception: I had a try
block without any except
or finally
blocks. This will not work:
try:
lets_do_something_beneficial()
To fix this, add an except
or finally
block:
try:
lets_do_something_beneficial()
finally:
lets_go_to_sleep()
answered Apr 15, 2019 at 21:05
There are some cases can lead to this issue, if it occered in the middle of the code it will be «IndentationError: expected an indented block» or «SyntaxError: invalid syntax», if it at the last line it may «SyntaxError: unexpected EOF while parsing»:
Missing the body of «if»,»while»and»for» statement—>
root@nest:~/workplace# cat test.py
l = [1,2,3]
for i in l:
root@nest:~/workplace# python3 test.py
File "test.py", line 3
^
SyntaxError: unexpected EOF while parsing
Unclosed parentheses (Especially in complex nested states)—>
root@nest:~/workplace# cat test.py
l = [1,2,3]
print( l
root@nest:~/workplace# python3 test.py
File "test.py", line 3
^
SyntaxError: unexpected EOF while parsing
answered May 14, 2020 at 23:51
tinyharetinyhare
2,22120 silver badges25 bronze badges
I encountered this error while trying to eval
an empty string.
for example:
query = eval(req.body)
I used json.loads()
instead and the error was gone.
answered May 28, 2021 at 12:36
Ali H. KudeirAli H. Kudeir
7142 gold badges9 silver badges19 bronze badges
elec_and_weather['DEMAND_t-%i'% k] = np.zeros(len(elec_and_weather['DEMAND']))'
The error comes at the end of the line where you have the (‘) sign; this error always means that you have a syntax error.
answered Jun 19, 2019 at 20:50
Sometimes its due to forgetting to add an Except on a try/except statement.
answered May 11, 2022 at 15:28
1
I got the same error below:
SyntaxError: unexpected EOF while parsing
When I forgot a trailing parenthesis as shown below:
print("Hello"
↑
Here
Or, when I forgot to put pass
to class or function as shown below:
class Person:
# pass
def test():
# pass
answered Nov 16, 2022 at 0:19
SyntaxError: unexpected EOF while parsing
SyntaxError: unexpected EOF while parsing
EOF stands for «end of file,» and this syntax error occurs when Python detects an unfinished statement or block of code. This can happen for many reasons, but the most likely cause is missing punctuation or an incorrectly indented block.
In this lesson, we’ll examine why the error SyntaxError: unexpected EOF while parsing
can occur. We’ll also look at some practical examples of situations that could trigger the error, followed by resolving it.
The most common cause of this error is usually a missing punctuation mark somewhere. Let’s consider the following print
statement:
As you may have noticed, the statement is missing a closing parenthesis on the right-hand side. Usually, the error will indicate where it experienced an unexpected end-of-file, and so all we need to do here is add a closing parenthesis where the caret points.
In this case, adding in the closing parenthesis has shown Python where print statement ends, which allows the script to run successfully.
This occurrence is a reasonably simple example, but you will come across more complex cases, with some lines of code requiring multiple matchings of parentheses ()
, brackets []
, and braces {}
.
To avoid this happening, you should keep your code clean and concise, reducing the number of operations occurring on one line where suitable. Many IDEs and advanced text editors also come with built-in features that will highlight different pairings, so these kinds of errors are much less frequent.
Both PyCharm (IDE) and Visual Studio Code (advanced text editor) are great options if you are looking for better syntax highlighting.
Building on the previous example, let’s look at a more complex occurrence of the issue.
It’s common to have many sets of parentheses, braces, and brackets when formatting strings. In this example, we’re using an f-string to insert variables into a string for printing,
example_list = [1, 2, 3, 4, 5]
for i, item in enumerate(example_list):
print(f'index : {i} value : {item}'
Out:
File "<ipython-input-3-babbd3ba1063>", line 4
print(f'index : {i} value : {item}'
^
SyntaxError: unexpected EOF while parsing
Like the first example, a missing parenthesis causes the error at the end of the print statement, so Python doesn’t know where the statement finishes. This problem is corrected as shown in the script below:
example_list = [1, 2, 3, 4, 5]
for i, item in enumerate(example_list):
print(f'index : {i} value : {item}')
Out:
index : 0 value : 1
index : 1 value : 2
index : 2 value : 3
index : 3 value : 4
index : 4 value : 5
In this situation, the solution was the same as the first example. Hopefully, this scenario helps you better visualize how it can be harder to spot missing punctuation marks, throwing an error in more complex statements.
The following code results in an error because Python can’t find an indented block of code to pair with our for
loop. As there isn’t any indented code, Python doesn’t know where to end the statement, so the interpreter gives the syntax error:
example_list = [1, 2, 3, 4, 5]
for item in example_list:
Out:
File "<ipython-input-5-5927dfecd199>", line 3
for item in example_list:
^
SyntaxError: unexpected EOF while parsing
A statement like this without any code in it is known as an empty suite. Getting the error, in this case, seems to be most common for beginners that are using an ipython console.
We can remedy the error by simply adding an indented code block:
example_list = [1, 2, 3, 4, 5]
for item in example_list:
print(item)
In this case, going with a simple print
statement allowed Python to move on after the for
loop. We didn’t have to go specifically with a print
statement, though. Python just needed something indented to detect what code to execute while iterating through the for
loop.
When using try
to handle exceptions, you need always to include at least one except
or finally
clause. It’s tempting to test if something will work with try
, but this is what happens:
Out:
File "<ipython-input-7-20a42a968335>", line 2
print('hello')
^
SyntaxError: unexpected EOF while parsing
Since Python is expecting at least one except
or finally
clause, you could handle this in two different ways. Both options are demonstrated below.
try:
print('hello')
except:
print('failed')
try:
print('hello')
finally:
print('printing anyway')
Out:
hello
printing anyway
In the first option, we’re just making a simple print statement for when an exception occurs. In the second option, the finally
clause will always run, even if an exception occurs. Either way, we’ve escaped the SyntaxError!
This error gets triggered when Python can’t detect where the end of statement or block of code is. As discussed in the examples, we can usually resolve this by adding a missing punctuation mark or using the correct indentation. We can also avoid this problem by keeping code neat and readable, making it easier to find and fix the problem whenever the error does occur.