Ситуация: программисту нужно вывести все числа по очереди от 1 до 10. Если он параллельно с Python осваивает несколько других языков, то иногда может организовать цикл так:
for i in range(10):
print(i)
Но при выполнении такого кода компьютер выдаст ошибку:
File «temp.py», line 2
print(‘Привет Мир!’)
^
❌ IndentationError: expected an indented block
Почему так происходит: компьютер знает, что в Python после двоеточия в цикле идёт тело цикла, которое отделяется отступами. В нашем коде команда цикла начинается на том же уровне, что и начало цикла, а в Python так не принято. Компилятор ругается, что не хватает отступов, и просит обратить на это внимание.
Что делать с ошибкой IndentationError: expected an indented block
Чтобы исправить ошибку, достаточно поставить отступы перед нужными командами:
for i in range(10):
print(i)
Единственное, нужно не запутаться в отступах и добавить их только там, где нужна вложенность, иначе сломается логика программы.
Практика
Попробуйте найти ошибки в этих фрагментах кода, а также найдите среди них код без ошибок:
for i in range(10):
print(i)
for i in range(10): print(i)
for i in range(10):
print(i)
for i in range(10):
print(i+1)
There are in fact multiples things you need to know about indentation in Python:
Python really cares about indention.
In a lot of other languages the indention is not necessary but improves readability. In Python indentation replaces the keyword begin / end
or { }
and is therefore necessary.
This is verified before the execution of the code, therefore even if the code with the indentation error is never reached, it won’t work.
There are different indention errors and you reading them helps a lot:
1. «IndentationError: expected an indented block»
They are two main reasons why you could have such an error:
— You have a «:» without an indented block behind.
Here are two examples:
Example 1, no indented block:
Input:
if 3 != 4:
print("usual")
else:
Output:
File "<stdin>", line 4
^
IndentationError: expected an indented block
The output states that you need to have an indented block on line 4, after the else:
statement
Example 2, unindented block:
Input:
if 3 != 4:
print("usual")
Output
File "<stdin>", line 2
print("usual")
^
IndentationError: expected an indented block
The output states that you need to have an indented block line 2, after the if 3 != 4:
statement
— You are using Python2.x and have a mix of tabs and spaces:
Input
def foo():
if 1:
print 1
Please note that before if, there is a tab, and before print there is 8 spaces.
Output:
File "<stdin>", line 3
print 1
^
IndentationError: expected an indented block
It’s quite hard to understand what is happening here, it seems that there is an indent block… But as I said, I’ve used tabs and spaces, and you should never do that.
- You can get some info here.
- Remove all tabs and replaces them by four spaces.
- And configure your editor to do that automatically.
2. «IndentationError: unexpected indent»
It is important to indent blocks, but only blocks that should be indent.
So basically this error says:
— You have an indented block without a «:» before it.
Example:
Input:
a = 3
a += 3
Output:
File "<stdin>", line 2
a += 3
^
IndentationError: unexpected indent
The output states that he wasn’t expecting an indent block line 2, then you should remove it.
3. «TabError: inconsistent use of tabs and spaces in indentation» (python3.x only)
- You can get some info here.
- But basically it’s, you are using tabs and spaces in your code.
- You don’t want that.
- Remove all tabs and replaces them by four spaces.
- And configure your editor to do that automatically.
Eventually, to come back on your problem:
Just look at the line number of the error, and fix it using the previous information.
The IndentationError: expected an indented block error indicates that you have an indentation error in the code block, which is most likely caused by a mix of tabs and spaces. The indentation is expected in an indented block. The IndentationError: expected an indented block error happens when you use both the spaces and tabs to indent in your code. The indent is expected in a block. To define a code block, you may use any amount of indent, but the indent must match exactly to be at the same level.
The python IndentationError: expected an indented block error occurs when you forget to indent the statements within a compound statement or within a user-defined function. In python, the expected an indented block error is caused by a mix of tabs and spaces. If you do not have appropriate indents added to the compound statement and the user defined functions, the error IndentationError: expected an indented block will be thrown.
The indent is known as the distance or number of empty spaces between the line ‘s beginning and the line’s left margin. The intent is used in order to make the code appear better and be easier to read. In python, the intent is used to describe the structure of the compound statement and the user-defined functions
Exception
In the compound statement and the user-defined functions, the inside code must be indented consistently. If you failed to add an indent, the error IndentationError: expected an indented block is shown. The error message suggests that the code lacks indentation.
The error IndentationError: expected an indented block is shown to be like the stack trace below. The error message displays the line that the indent is supposed to be added to.
File "/Users/python/Desktop/test.py", line 5
print "hello world";
^
IndentationError: expected an indented block
[Finished in 0.0s with exit code 1]
Root Cause
Python is the sentivite language of indentation. Compound statement and functions require an indent before starting a line. The error message IndentationError: expected and indented block is thrown due to a lack of indent in the line that the python interpreter expects to have.
There’s no syntax or semantic error in your code. This error is due to the style of writing of the program
Solution 1
In most cases, this error would be triggered by a mixed use of spaces and tabs. Check the space for the program indentation and the tabs. Follow any kind of indentation. The most recent python IDEs support converting the tab to space and space to tabs. Stick to whatever format you want to use. This is going to solve the error.
Check the option in your python IDE to convert the tab to space and convert the tab to space or the tab to space to correct the error.
Solution 2
In the sublime Text Editor, open the python program. Select the full program by clicking on Cntr + A. The entire python code and the white spaces will be selected together. The tab key is displayed as continuous lines, and the spaces are displayed as dots in the program. Stick to any format you wish to use, either on the tab or in space. Change the rest to make uniform format. This will solve the error.
Program
a=10;
b=20;
if a > b:
print "Hello World"; ----> Indent with tab
print "end of program"; ----> Indent with spaces
Solution
a=10;
b=20;
if a > b:
print "Hello World"; ----> Indent with tab
print "end of program"; ----> Indent with tab
Solution 3
The program has no indentation where the python interpreter expects the indentation to have. The blocks are supposed to have an indentation before the beginning of the line. An indentation should be added in line 4 in the example below
Program
a=20;
b=10;
if a > b:
print "hello world";
Output
File "/Users/python/Desktop/test.py", line 5
print "hello world";
^
IndentationError: expected an indented block
Solution
a=20;
b=10;
if a > b:
print "hello world";
Output
hello world
[Finished in 0.0s]
Solution 4
Python may have an incomplete block of statements. There may be a missing statement in the block. Some of the lines may be incomplete or deleted from the program. This is going to throw the indentation error.
Add missing lines to the program or complete the pending programming. This is going to solve the error.
program
a=20;
b=10;
if a > b:
print "hello world";
else:
Solution
a=20;
b=10;
if a > b:
print "hello world";
else:
print "hello world in else block";
Output
hello world
[Finished in 0.0s]
Solution 5
In the above program, if the else block is irrelevant to logic, remove the else block. This will solve the indent error. The Python interpreter helps to correct the code. Unnecessary code must be removed in the code.
Program
a=20;
b=10;
if a > b:
print "hello world";
else:
Output
File "/Users/python/Desktop/test.py", line 5
print "hello world";
^
IndentationError: expected an indented block
Solution
a=20;
b=10;
if a > b:
print "hello world";
Output
hello world
[Finished in 0.0s]
Solution 6
In the python program, check the indentation of compound statements and user defined functions. Following the indentation is a tedious job in the source code. Python provides a solution for the indentation error line to identify. To find out the problem run the python command below. The Python command shows the actual issue.
Command
python -m tabnanny test.py
Example
$ python -m tabnanny test.py
'test.py': Indentation Error: unindent does not match any outer indentation level (<tokenize>, line 3)
$
Solution 7
There is an another way to identify the indentation error. Open the command prompt in Windows OS or terminal command line window on Linux or Mac, and start the python. The help command shows the error of the python program.
Command
$python
>>>help("test.py")
Example
$ python
Python 2.7.16 (default, Dec 3 2019, 07:02:07)
[GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.37.14)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> help("test.py")
problem in test - <type 'exceptions.IndentationError'>: unindent does not match any outer indentation level (test.py, line 3)
>>>
Use exit() or Ctrl-D (i.e. EOF) to exit
>>> ^D
Отступы в Python строгие. Очень важно соблюдать их в коде.
Если неправильно организовать отступы, пробелы или табуляции в программе, то вернется ошибка IndentationError: expected an intended block
.
В этом руководстве рассмотрим, что это за ошибка и когда она появляется. Разберем пример и посмотрим, как решить эту проблему.
Языки программирования, такие как C и JavaScript, не требуют отступов. В них для структуризации кода используются фигурные скобы. В Python этих скобок нет.
Структура программы создается с помощью отступов. Без них интерпретатор не сможет корректно распознавать разные блоки кода. Возьмем такой код в качестве примера:
def find_average(grades):
average = sum(grades) / len(grades)
print(average)
return average
Откуда Python знает, какой код является частью функции find_average()
, а какой — основной программы? Вот почему так важны отступы.
Каждый раз, когда вы забываете поставить пробелы или символы табуляции, Python напоминает об этом с помощью ошибки отступа.
Пример возникновения ошибки отступа
Напишем программу, которая извлекает все бублики из списка с едой в меню. Они после этого будут добавлены в отдельный список.
Для начала создадим список всей еды:
lunch_menu = ["Бублик с сыром", "Сэндвич с сыром", "Cэндвич с огурцом", "Бублик с лососем"]
Меню содержит два сэндвича и два бублика. Теперь напишем функцию, которая создает новый список бубликов на основе содержимого списка lunch_menu
:
def get_bagels(menu):
bagels = []
for m in menu:
if "Бублик" in m:
bagels.append(m)
return bagels
get_bagels()
принимает один аргумент — список меню, по которому она пройдется в поиске нужных элементов. Она проверяет, содержит ли элемент слово «Бублик», и в случае положительного ответа добавит его в новый список.
Наконец, функцию нужно вызвать и вывести результат:
bagels = get_bagels(lunch_menu)
print(bagels)
Этот код вызывает функцию get_bagels()
и выводит список бубликов в консоль. Запустим код и посмотрим на результат:
File "test.py", line 4
bagels = []
^
IndentationError: expected an indented block
Ошибка отступа.
Решение ошибки IndentationError
Ошибка отступа сообщает, что отступ был установлен неправильно. Его нужно добавить на 4 строке. Посмотрим на код:
def get_bagels(menu):
bagels = []
Значение переменной bagels
должно присваиваться внутри функции, но этого не происходит, что и приводит к ошибке. Для решения проблемы нужно добавить отступ:
def get_bagels(menu):
bagels = []
Теперь запустим код:
['Бублик с сыром', 'Бублик с лососем']
Код нашел все бублики и добавил их в новый список. После этого вывел его в консоль.
Вывод
Ошибка IndentationError: expected an indented block возникает, если забыть добавить отступ в коде. Для исправления нужно проверить все отступы, которые должны присутствовать.
Indentation is more important in Python than many languages, so much so that it can cause errors. Learn how to deal with the most common problem.
Indentation is a vital feature of readable, maintainable code, but few languages enforce it. Python is one of those few.
If Python determines your code is indented incorrectly, you’ll be seeing the “IndentationError” message when you run your code. But how do you fix this, and how do you prevent it in the future?
Why Do You Get the IndentationError in Python?
The “IndentationError: expected an indented block” error is something you’re likely to see when you first start using Python, especially if you’ve come from another programming language.
The specifics of Python’s indentation rules are complex, but they boil down to one thing: indent code in blocks. This goes for functions, if clauses, and so on. Here’s an example of incorrectly formatted Python code:
fname = "Gaurav"lname = "Siyal"
if fname == "Gaurav" and lname == "Siyal":
print("You're Gaurav")
else:
print("You're somebody else")
When you try to run the above code, you’ll get a message like this:
File "tmp.py", line 5 print("You're Gaurav")
^
IndentationError: expected an indented block
Instead, you should add either a tab or a series of spaces at the start of the two lines that represent blocks:
fname = "Gaurav"
lname = "Siyal" if fname == "Gaurav" and lname == "Siyal":
print("You're Gaurav")
else:
print("You're somebody else")
If you indent with spaces, you can actually use any number you like, so long as you’re consistent and unambiguous. Most programmers use two, four, or eight spaces.
Common Cases of Correct Indentation
Here are some examples that you can refer to, so you can ensure you’re indenting correctly.
If statements
Indent the block that follows an if statement:
if my_name == "Gaurav":
print("My name is Gaurav")
return True
Functions
The body of a function is a block. You should indent this entire block:
def magic_number():
result = 42
return result print magic_number()
For Loops
As with an if statement, the body of a for loop should be indented one level more than the line starting with the for keyword:
for i in range(10):
print (i)
Make Sure Your Editor Indents Correctly
Most modern text editors support automatic code indentation. If your editor determines that a line of code should be indented, it will add tabs or spaces automatically.
In Spyder, indentation options are available under Tools > Preferences > Source code:

If you’re using vim, you can edit your configuration and use the autoindent and related options to configure indentation. For example, here’s a common setup:
set autoindent
set expandtab
set tabstop=4
set softtabstop=4
set shiftwidth=4
This will automatically indent using four spaces.
However, no editor can make automatic indentation bulletproof. You’ll still need to pay attention to indenting because some cases are ambiguous:

In this example, the final return statement is indented one level in from the function signature on the first line. However, if you position your cursor at the end of the penultimate line and press Enter, one of two things may happen. Your editor could position the cursor:
- Two indent levels in, aligned with «res =…»
- One indent level in, aligned with the «else:»
Your editor cannot distinguish between these two cases: you may want to add more code in the if/else block, or you may not.
Handling Python’s ‘Expected an Indented Block’ Error
Errors are an everyday occurrence in Python, just as in any other programming language. Python’s strict rules about indentation may add a new kind of error to think about, but they are useful. Properly indented code is more readable and consistent across teams.
The indentation error is not the only one you’ll have to deal with. It helps to be familiar with common Python errors so you know how to debug them and what to do to fix them.