Indentationerror expected an indented block что означает ошибка

Ситуация: программисту нужно вывести все числа по очереди от 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.

IndentationError: expected an indented block

IndentationError: expected an indented block

As the error implies, this occurs after statements that require indenting, such as after if statements, for loops and try except exception handling.

Unlike many programming languages that use braces, Python requires indents to determine which code block belongs to a statement. More simply, after detecting the : character in your script, Python will look for an indent.

This lesson will quickly examine a few reasons when this error can occur and how to fix it.

Imagine you are looking at sales figures for Company A, which sells software packages. You want to write a script for determining which employees are meeting a certain sales threshold.

Using enumerate, we can iterate through employees and use the index as an ID for each employee. We can then print off a message showing if that employee hit the sales target or not.

The script below shows how we can execute this process:

company_employee_sales = [58, 39, 52]

for employee_id, employee_sales in enumerate(company_employee_sales):
print(f'Employee {employee_id + 1}:')

if employee_sales > 50:
    print('Hit sales target!n')
else:
    print('Room for improvement.n')

Out:

File "<ipython-input-7-8f5233f8cf0e>", line 4
    print(f'Employee {employee_id + 1}:')
    ^
IndentationError: expected an indented block

Although we’ve made the if else loop correctly, the for statement is causing an indentation error. This error is happening because we’ve provided a list for Python to iterate through in our for loop, but it doesn’t know which logic it needs to apply while looping.

The straightforward fix is to add an indent at the line indicated in the error:

company_employee_sales = [58, 39, 52]

for employee_id, employee_sales in enumerate(company_employee_sales):
    print(f'Employee {employee_id + 1}:')

if employee_sales > 50:
    print('Hit sales target!n')
else:
    print('Room for improvement.n')

Out:

Employee 1:
Employee 2:
Employee 3:
Hit sales target!

Now that Python has the correct structure, it will check the sales figure for each employee individually and consider if the number is greater than 50 or not. It will then print the corresponding message and move on to the next employee.

When working on larger scripts, you’ll often anticipate many if elif branches ahead of time by creating a branch and commenting on some logic you plan on filling in later.

Here’s an example using our sales analysis script that we used previously:

company_employee_sales = [58, 39, 52]

for employee_id, employee_sales in enumerate(company_employee_sales):
    print(f'Employee {employee_id + 1}:')
    if employee_sales > 50:
        # add functionality here to display that the employee hit their target
    else:
        print('Room for improvement.')

Out:

File "<ipython-input-9-d1e1fb64bfe8>", line 7
    else:
    ^
IndentationError: expected an indented block

In this case, Python throws the error because it’s looking for a code block after the if statement, i.e., what your program should do if the statement is true. The code seems to be structured correctly, but the program will fail to run until the actual code is placed after the if.

Having a statement like this without anything following it is known as an empty suite. A quick fix for this is to use the pass keyword:

company_employee_sales = [58, 39, 52]

for employee_id, employee_sales in enumerate(company_employee_sales):
    print(f'Employee {employee_id + 1}:')
    if employee_sales > 50:
        # add functionality here to display that the employee hit their target
        pass
    else:
        print('Room for improvement.')

Out:

Employee 1:
Employee 2:
Room for improvement.
Employee 3:

In this situation, the pass keyword allows Python to skip when the if is true. This command bypasses the indentation error, allowing us to work on other areas until we are ready to come back and write the functionality that displays a message.

To keep code well-documented, we can use docstrings at the start of a function, class, or method to quickly say what the code does. This description is to make life easier for yourself and others when reviewing the code later.

To write a docstring, you use two sets of triple apostrophes (»’) or quotes («»»), which makes multi-line comments in Python possible.

The example below shows how we can use a docstring to describe a function to contain the if-else loop we’ve been using in our sales analysis script.

def analyze_sales(sales_figure):
'''function used for taking sales figures as an input and outputting a message related to the target'''
    if sales_figure > 50:
        message = 'Hit sales target!n'
    else:
        message = 'Room for improvement.n'
    return message


company_employee_sales = [58, 39, 52]

for employee_id, employee_sales in enumerate(company_employee_sales):
    print(f'Employee {employee_id + 1}:')
    print(analyze_sales(employee_sales))

Out:

File "<ipython-input-13-e17405f37406>", line 2
    '''function used for taking sales figures as an input and outputting a message related to the target'''
    ^
IndentationError: expected an indented block

This script crashed because Python is looking for indentation at the start of the function. To fix this, we can add an indent to the docstring. Shown below is this solution in action:

def analyze_sales(sales_figure):
    '''function used for taking sales figures as an input and outputting a message related to the target'''
    if sales_figure > 50:
        message = 'Hit sales target!n'
    else:
        message = 'Room for improvement.n'
    return message


company_employee_sales = [58, 39, 52]

for employee_id, employee_sales in enumerate(company_employee_sales):
    print(f'Employee {employee_id + 1}:')
    print(analyze_sales(employee_sales))

Out:

Employee 1:
Hit sales target!

Employee 2:
Room for improvement.

Employee 3:
Hit sales target!

Note that in this example, using a regular comment (#) to mark the docstring would prevent the indentation error without the need to add an indent. Avoid doing this, though, as it’s best practice to keep docstrings within two sets of triple apostrophes/quotes.

This error occurs when Python is looking for an indented block of code after certain types of statements. The indented block tells Python that the code within the block is relevant to the statement. This s}tructure is fundamental to the Python programming language, so it’s no surprise incorrectly indenting things can make scripts malfunction! Luckily, this is an easy fix, and in most cases, all you need to do is quickly add an indent in the correct place, and you’ll be good to go.

Отступы в 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 возникает, если забыть добавить отступ в коде. Для исправления нужно проверить все отступы, которые должны присутствовать.

Error handling is one of the best features of Python. With known error Exceptions, you can reduce the bugs in your program. As Python operates on indentation blocks for deducing the inside block for any statement, you may encounter IndentationError: Expected An Indented Block Error.

IndentationError: Expected An Indented Block Error is a known error in python which is thrown when an indented block is missing from the statement. IndentationError states that there is an error related to the Indentation of general statements in your code. In Python, general statement blocks expect an indentation in child statements. If you fail to provide these indentations, Indentation Error will arise.

In this tutorial, we will be discussing a new type of error, i.e., IndentationError: expected an indented block. We all know c, c++, and java when we write any loop, conditional statements, or function code inside the brackets. But in python, it is actually part of this programming language.

What is meant by Indentation?

The meaning of Indentation in python is the space from margin to the beginning of characters in a line. Where in other programming languages, indentation is just for the sake of the readability purpose. But in python, indentation is necessary.

In most popular programming languages like c, c++, and java, spaces or indentation are just used to make the code look good and be easier to read. But In Python, it is actually part of this programming language. Because python is the sensitive language for indentation, many beginners face confusion or problems in the starting as Putting in extra space or leaving one out where it is needed will surely generate an error message. Some causes of indentation error are:

  • When we forget to indent the statements within a compound statement
  • When we forget to indent the statements of a user-defined function.

The error message IndentationError: expected an indented block would seem to indicate that you have a spaces error or indentation error.

Examples of IndentationError: Expected an indented block

Here are some examples through which you will know about the Indentation error: expected an indented block.

1. IndentationError: Expected an indented block in IF condition statements

In this example, we will be using the if condition for writing the code and seeing the particular error. We have taken two variables, ‘a’ and ‘b,’ with some integer value. Then, applied if condition and no indented the if block. Let us look at the example for understanding the concept in detail.

a=10
b=20
if b>a:
print("b is greater than a")

Output:

IndentationError: Expected an indented block in IF condition statements

Explanation:

  • Firstly, we have taken two variables, ‘a’ and ‘b,’ and assigned the values 10 and 20 in them.
  • Then, we have applied if condition.
  • And at last, without giving the indentation block of if statement we have printed b is greater than a.
  • Hence, we have seen the output as IndentationError: expected an indented block.

2. If-else condition for seeing the error as expected an indented block

In this example, we will be using the if-else condition for writing the code and seeing the particular error. We have taken two variables, ‘a’ and ‘b,’ with some integer value. Then, applied the if-else condition and indented the if block but not the else block. So let’s see which error occurs. Let us look at the example for understanding the concept in detail.

If-else condition for seeing the error as expected an indented block

a=10
b=20
if b>a:
    print("b is greater than a")
else:
print("b is smaller than a")

Output:

Explanation:

  • Firstly, we have taken two variables, ‘a’ and ‘b,’ and assigned the values 10 and 20 in them.
  • Then, we have applied the if-else condition.
  • In the if condition, we have applied the tab space but not in the else condition.
  • And at last, without giving the indentation block of else statement, we have tried to print b is smaller than a.
  • Hence, we have seen the output as IndentationError: expected an indented block.

3. Indentation Error: expected an indented block in Docstring Indentation

In this example, we will be showing that the error can also come up if the programmer forgets to indent a docstring. Docstrings must be in the same line with the rest of the code in a function. The Docstring processing tools will strip an amount of indentation from the second and further lines of the docstring, equal to the minimum indentation of all unblank lines after the first line. Let us look at the example for understanding the concept in detail.

def pythonpool():
"""This is a comment docstring"""
    print("Hello")


#fixing this error as
#def pythonpool():
#    """This is a comment docstring"""
#    print("Hello")

Output:

4. Indentation Error: expected an indented block in Tabbed Indentation

In this example, we will see the indentation error in the tabbed indentation. As you can see in the code, while writing “This is a comment docstring,” we have passed the tab space for an indent, and in print () there is less indent. so this will produce a tabbed indentation. Let us look at the example for understanding the concept in detail.

def pythonpool():
    """This is a comment docstring"""
  print("Hello")

Output:

5. Indentation Error: expected an indented block in empty class/function

 Indentation Error: expected an indented block in empty class/function

In this example, we will see the error in an empty class. We have declared two classes with the name as EmptyClass and MainClass. But in Class EmptyClass, we didn’t pass (statement) any indent, so it generated the error. Let us look at the example for understanding the concept in detail.

#error code
class EmptyClass:
class MainClass:
    pass

#solution code
class EmptyClass:
    pass
class MainClass:
    pass

Output:

Where Indentation is required?

The indentation is required in the python block. Whenever you encounter a colon(:) is a line break, and you need to indent your block. Python uses white space to distinguish code blocks. You are allowed to use spaces and tabs to create a python block. When several statements in python use the same indentation, they are considered as a block. Basically, Indentation is required to create a python block or write the loop, conditional statements, and user-defined function you require indentation.

How to solve the IndentationError: expected an indented block

To solve this error, here are some key points which you should remember while writing the program or code:

  • In your code, give the indent with only the tab spaces, equal to every loop, conditional, and user-defined function.
  • Otherwise, in your code, give the indent with only the spaces equal to every loop, conditional, and user-defined function.

Examples of solved IndentationError: expected an indented block

Here are some examples through which you will know how to solve the error Indentation error: expected an indented block.

1. If-else conditional statement indentation

In this example, we will be using the if-else condition for writing the code and seeing the particular output. We have taken two variables, ‘a’ and ‘b,’ with some integer value. After this, I applied the if-else condition with a proper indentation in both conditions and printed the output. Let us look at the example for understanding the concept in detail.

a=10
b=20
if b>a:
    print("b is greater than a")
else:
    print("b is smaller than a")

Output:

Explanation:

  • Firstly, we have taken two variables, ‘a’ and ‘b,’ and assigned the values 10 and 20 in them.
  • Then, we have applied the if-else condition.
  • While applying the if-else condition, we have given the proper indentation of a tab in both the condition of if and as well as of else condition.
  • And printed the output after checking the condition.
  • Hence, we have seen the output without any IndentationError: expected an indented block error.

2. For loop statement indentation

In this example, we have applied for loop and printed the output while giving the proper indentation for the loop block. Let us look at the example for understanding the concept in detail.

for i in range(1,10):
    print(i)

Output:

Explanation:

  • In this example, we have applied for loop.
  • The for loop is starting from 1 and going till 10.
  • And with proper indent, we have printed the value of i.
  • Hence, you can see the correct output without any error.

How to fix indentation in some code editors

1. Sublime text

For setting the indentation in sublime text editor you need to perform the following steps:

To set the Indentaion to tabs

  • Go to view option.
  • Choose Indentation.
  • Convert Indentation to tabs.

And go to the sub-menu and look for the ‘Indent Using Spaces’ option and uncheck it.

2. VS code

For setting the indentation in VS code text editor you need to perform the following steps:

  • Go to the File menu.
  • Choose preferences.
  • Choose settings.
  • Type tabsize in the search bar.
  • Then, uncheck the checkbox of Detect Indentation.
  • Change the tab size to 2 or 4 according to your choice.

3. Pycharm

For setting the indentation in Pycharm text editor you need to perform the following steps:

  • Go to the File menu.
  • Choose settings.
  • Then, Choose the editor.
  • Choose code style.
  • Choose Python.
  • And choose tabs and indents.
  • Suppose it is set to 0. please set it to 4. which is recommended by PEP8.

Conclusion

In this tutorial, we have learned the concept of IndentationError: expected an indented block. We have seen what Indentation is, what indentation error is, how indentation error is solved, why it is required to solve the indentation error. We have also explained the examples of showing the IndentationError: expected an indented block and the examples of showing the solution of the given error. All the examples are explained in detail with the help of examples.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Other Typical Python Errors

  • How to Solve TypeError: ‘int’ object is not Subscriptable
  • 4 Quick Solutions To EOL While Scanning String Literal Error
  • Invalid literal for int() with base 10 | Error and Resolution
  • NumPy.ndarray object is Not Callable: Error and Resolution
  • How to Solve “unhashable type: list” Error in Python

FAQs

1. What does expected an indented block mean in Python?

Excepted an indented block error in python, we must have at least one line of code while writing the function, conditional statements, and loops. We can also say that a conditional must have at least one line of code to run if the condition is true.

2. How to follow pep8 format to avoid getting IndentationError?

PEP8 formats says to you should follow 4 spaces indentation to avoid getting error.

3. Explain why this error is mostly generated in code editors like sublime.

This error is mostly generated in sublime as it does not follows PEP8 format, i.e., 4 spaces indentation. Sublime text editor follows tabs as indentation, so there are most chances to get the indentation error.

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

To fix the IndentationErrorexpected an indented block error in Python, indent the block of code correctly to align it with its surrounding code.

The IndentationErrorexpected an indented block error occurs in Python when the code is not indented correctly. To solve an expected indented block error in Python, correct the indentation of each block. In Python, Indentation is part of the syntax.

In Python, whitespace (indentation) is significant and determines the scope of a code block.

An “IndentationError: expected an indented block” means that a block of code that is supposed to be indented is not indented at all or not indented enough, which leads the interpreter to believe that the block of code is not part of the current scope.

Before Python runs any code in your program, it will first discover each line’s correct parent and children. Then, Python throws an Indentation whenever it comes across a line for which it cannot define the right parent to assign.

def compare(num):
 if num >= 1:
 print("It is positive number")
 elif num < 0:
 print("It is negative number")
 else:
 print("It is zero") 


compare(1)

If you run the above file, your output looks like the one below.

 File "/Users/krunal/Desktop/code/pyt/database/app.py", line 3
 print("It is positive number")
 ^
IndentationError: expected an indented block

Other causes of the error

The causes of the IndentationError: expected an indented block error include:

  1. Incorrect indentation levels: The code is not indented to the proper level
  2. Mixing tabs and spaces for indentation causes inconsistencies, leading to the error message.
  3. Improper use of white space characters: Using extra spaces or the wrong type of white space character can result in an error.

Python really cares about indention

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.

From the above example, you can check if you have left alone an elif: part of an if-condition, and check if the indentation is missing after conditions, loops, etc.

In our example, there should be an indentation before starting a new statement after the if, elif, and else blocks.

Still, we did not put any whitespace, and that caused an indentation error. So let’s resolve the error by providing whitespaces.

def compare(num):
 if num >= 1:
 print("It is positive number")
 elif num < 0:
 print("It is negative number")
 else:
 print("It is zero")


compare(1)

Output

And the IndentationError is successfully resolved.

For example, Python statements start with def or must have at least one child. This means that a function must have at least one line of code. It also means that a conditional must have at least one line of code to run if the condition is True.

Let’s see the example in which we don’t write anything after the first if statement.

def compare(num):
 if num >= 1:
 
 elif num < 0:
 print("It is negative number")
 else:
 print("It is zero")


compare(1)

Output

File "/Users/krunal/Desktop/code/pyt/database/app.py", line 4
 elif num < 0:
 ^
IndentationError: expected an indented block

After Python reads the if statement, it expects to see at least one child line following it. However, since the next non-empty line reads it is the elif statement, which means the if statement has no children, Python reports that it expected some indented lines.

To fix this IndentationError, either place at least one line of code as the if statement’s child or remove them entirely.

def compare(num):
 if num >= 1:
   print("It is positive number")
 elif num < 0:
   print("It is negative number")
 else:
   print("It is zero")


compare(1)

If you run the above code, you will get the expected output.

Python unexpected indent

Python throws an IndentationError when it finds a line indented as if the line had some parent line, but it couldn’t get any lines above to be its parent.

For example, you face this unexpected indent error when a line is indented by one or more spaces more than the previous line, and the previous line isn’t def, if, elif, else, for, or while loop.

That is it for IndentationError in Python and how to resolve it.

Conclusion

Importance of proper indentation

  1. Code readability: Use the proper indentation that makes the code easier to read and understand, especially for other people working on the same code in the future.

  2. Code structure: Indentation is used to indicate the structure and hierarchy of the code, making it easier to identify the relationships between different code blocks.
  3. Debugging:  Proper indentation can help quickly identify and fix code errors.
  4. Syntax errors: Incorrect indentation can result in syntax errors, preventing the code from running as expected.

Emphasis on avoiding the error in the future

  1. Adhere to a consistent indentation style: Whether you use tabs or spaces, make sure to use them consistently throughout your code.

  2. Use a code editor with syntax highlighting: Some code editors will highlight indentation errors, making them easier to spot and correct.
  3. Regularly review your code: Make it a habit to periodically review your code and ensure that the indentation is correct and consistent.
  4. Get in the habit of checking your code before running it: Checking your code for proper indentation can help prevent errors from occurring in the first place.

That’s it.

Python error: expected an indented block been causing trouble?

At Bobcares, we offer solutions for every query, big and small, as a part of our Server Management Service.

Let’s take a look at how our Support Team recently helped a customer with the commonly seen indentation error in Python error.

What is Python error: “Expected an indented block”?

If you have been using spaces and tabs incorrectly, you are sure to run into the “IndentationError: expected an indented block” error. Today, our Support Engineers are here to walk you through the error and help you figure out how to avoid it.

While other programming languages like JavaScript and C rely on curly braces to structure code blocks, Python relies on indentation. Furthermore, the indentation makes it easier to read Python code.

This is why it is critical to master Python indentation rules in order to stop running into the “Expected an indented block”.

How to resolve Python error: “Expected an indented block”

The main purpose of the IndentationError is to let us know when we incorrectly indent our code. As long as we indent the code correctly as seen in the image below, we can avoid the error:

Python error expected an indented blockFor instance,

site
if site == 'edu':
print('Logging in to Springfield School!')
else:
print('Please type the URL again.')
print('You are ready to go!')

This code will result in the “IndentationError: expected an indented block”. By adding the following indentation, we will be able to avoid the error:

site
if site == 'edu':
	print('Logging in to Springfield School!')
else:
	print('Please type the URL again.')
print('You are ready to go!')

Hence, we need to indent the code correctly in order to stay clear of the indentation error. According to our Support Team, ensuring that our code has the proper number of indents is all we need to do to make sure we do not face the error again.

[Looking for a solution to another query? We are just a click away.]

Conclusion

In essence, the skilled Support Engineers at Bobcares demonstrated how to deal with the indentation error in Python.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

Home > Data Science > Indentation Error in Python: Causes, How to Solve, Benefits

As an interpreted, high-level and general-purpose programming language, Python increasingly garners accolades as the programming world’s most promising, leading and emerging platforms. Python is nothing without its ingenious design philosophy.

A key characteristic is an emphasis drawn to the notable use of significant indentation to enhance code-readability. The illustration highlighted below briefly outlines Python’s design philosophy’s bulwarks as twenty aphorisms, alluded to by Tim Peters, long-term Pythoneer, who eventually became one of Python’s most prolific and tenacious core developers. 

A Brief Introduction to Python

Before we delve into the specific technicalities underlying the indentation error in Python, we must get acquainted with Python’s fundamentals and the need for indentation. Doing so will not only help you gain a better appreciation of the error itself but offer an insight into the advantages that programmers gain by effectively choosing to resolve the same.

The inception of Python as a multi-paradigm programming language can be traced back to the year 1991. Since then, programmers have continually adapted Python’s core wireframe to suit a range of user-specific needs, such as data science and web and mobile development. 

Now, we all know that attempting to comprehend illegible handwriting is painstakingly tricky and often infuriating. Similarly, an unreadable and unstructured code is plain and simple, unacceptable in the programming world. This is where the notion of PEP or Python Enhancement Proposal comes to the programmer’s rescue. PEP to the Python Community is akin to a shared Google Doc for the general populace.

It is a continually updated descriptive mandate that keeps the Python programming community comprehensively informed of features and updates to improve code readability. By Guido van Rossum, Barry Warsaw and Nick Coghlan in 2001, the PEP 8 is referred to as Python’s style code. 

Our learners also read – python online course free!

What is Indentation?

It is primarily known that Python is a procedural language, and therefore, an indentation in Python is used to segregate a singular code into identifiable groups of functionally similar statements. The majority of the programming languages, including C, C++ and JAVA, employ curly braces’ {}’ to define a code block. Python marks a deviation from this design and prefers the use of indentation. 

Syntax of Indentation

According to the conventions outlined by PEP 8 whitespace ethics, every new iteration (i.e., a block of code) should start with an indentation, and the ending of the code should be the first line that is not indented. The common practice to execute an indentation is four white spaces or a single tab character, with areas being largely preferred over tabs.

As discussed earlier, the leading whitespaces at the start of a line determine the line’s indentation level. To group the statements for a particular code block, you will have to increase the indent level. Similarly, to close the grouping, you will have to reduce the indent level. 

Checkout: 42 Exciting Python Project Topic & Ideas

Causes of Indentation Error in Python

The ‘Indentation Error: Expected an indented block’ does not discriminate between users. Whether you are a novice at Python programming or an experienced software developer, this is bound to happen at some point in time. In Python, since all the code you type is arranged via correct whitespaces, if at any instance in the code, you have an incorrect indentation, the overall code with not run, and the interpreter will return an error function. To know exactly what to keep an eye out for, the following lists some of the common causes of an indentation error in Python:

1. The simultaneous use of tabs and space while coding. It can be argued that in theory, both tabs and spaces serve the same purpose, but let us consider this from the perspective of the interpreter. If white spaces and tabs are used inconsistently and interchangeably, it creates ambiguity. This will result in the interpreter getting confused between which alteration to use and eventually returning an indentation error in Python.

2. You have unintentionally placed an indentation in the wrong place or an absence of tabs or white spaces between code lines. Since Python adheres to strict guidelines to arrange written codes, an indentation in the wrong place will inevitably return an error. For example, the first line of Python should not be indented. 

3. Occasionally, while finishing an overdue, exceptionally long program, you might unknowingly miss out on indenting compound statement functions such as for, while and if. This will again lead to an indentation error. This is the most basic need for indentation when using Python and needs to be rigorously practised to master.

4. If you have forgotten to use indentation when working with user-defined functions or different classes, an error is likely to pop up. 

upGrad’s Exclusive Data Science Webinar for you –

How upGrad helps for your Data Science Career?

Explore our Popular Data Science Courses

How to solve an indentation error in Python?

1. Check for wrong white spaces or tabs. Unfortunately, there is no quick fix to an indentation error. Since the code is yours, the fact remains that you will have to assess each line to identify erroneous instances individually. However, since lines of code are arranged in blocks, the process is relatively simple. For example, if you have used the ‘if’ statement in a particular sequence, you can cross-check if you have remembered to indent the following line.

2. Be certain that the indentation for a specific block remains the same throughout the code, even if a new block is introduced in the middle. Check for inconsistencies in the indentation.

If the above manual solutions did not work for you, and you are having a hard time figuring out where you missed the indentation, then follow these steps:

3. Go to your code editor settings and enable the option that seeks to display tabs and whitespaces. With this feature enabled, you will see single small dots, where each dot represents a tab/white space. If you notice a drop is missing where it shouldn’t be, then that line probably has an indentation error.

4. Use the Python interpreter built-in Indent Guide. Arguably, this method is highly inefficient for several code lines. However, since it takes you through each line and shows you exactly where your error lies, it is the surest way to find and fix all errors. 

Also Read: Top 12 Fascinating Python Applications in Real World

Read our popular Data Science Articles

Benefits of Indentation

Readability and consistency are essential for any good code. Following the PEP 8 whitespace, ethics should thus be non-negotiable. It logically substantiates your code, thereby contributing to a more pleasant coding experience. Additionally, if you follow this stylistic guideline where readability is your de facto, people who are unknown to you, but are interested in your work, will understand your code with ease. 

Disadvantages of Indentation              

  • If the code is large and the indentation is corrupted, it can be tedious to fix indentation errors. This is usually when a code is copying from an online source, Word document or PDF file. 
  • Popular programming languages typically use braces for indentation. For programmers just beginning to use Python, adjusting to the idea of using whitespaces for indentation can be difficult. 

Top Data Science Skills to Learn

Summing Up

All that lies between you and a well-written code is an indentation, and all that lies between you, your well-written code and its seamless execution is an indentation error. Now, all humans make mistakes. All programmers are humans. Therefore, all programmers make mistakes. But an indentation error can easily be resolved. All you need to do is breathe and take your space. 

I hope you will learn a lot while working on these python projects. If you are curious about learning data science to be in front of fast-paced technological advancements, check out upGrad & IIIT-B’s Executive PG Programme in Data Science and upskill yourself for the future.

What errors can I get due to indentation in Python?

Python determines when code blocks begin and stop by looking at the space at the beginning of the line. You may encounter the following Indentation errors:
1. Unexpected indent — This line of code has more spaces at the beginning than the one before it, but the one before it does not begin a subblock. In a block, all lines of code must begin with the same string of whitespace.
2. Unindent does not correspond to any of the outer indentation levels — This line of code contains less spaces at the beginning than the previous one, but it also does not match any other block.
3. An indented block was expected — This line of code begins with the same number of spaces as the previous one, yet the previous line was supposed to begin a block (e.g., if/while/for statement, function definition).

How do you fix inconsistent tabs and spaces in indentation Spyder?

Tabs and spaces are two separate characters that appear on the screen as whitespace. The issue is that there is no consensus on how big a tab character should be, thus some editors display it as taking up 8 spaces, others as 4 spaces, and others as 2, and it’s also customizable.
When you code but one line is indented with a tab and the other with spaces, Python throws an error, despite the fact that it seems good in the editor (but it won’t look fine if you double the width of a tab; now the tab lines will be indented two levels).
To avoid this problem, go to your text editor’s options and enable the convert tabs to spaces feature, which replaces the tab character with n space characters, where n is the tab width your editor uses.

How do you show indents on Spyder?

Select your code and press Tab or Shift + Tab to indent or un-indent it. Other tools for altering your code can be found in the Edit section.

Want to share this article?

Prepare for a Career of the Future

Понравилась статья? Поделить с друзьями:
  • Incorrect syntax near sql ошибка
  • Incorrect authentication data ошибка почты
  • Inconsistent use of tabs and spaces in indentation ошибка
  • Inconsistent address and mask в чем ошибка
  • Incomplete session by time out ошибка принтера xerox