Indentationerror expected an indented block python ошибка

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.

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

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 строгие. Очень важно соблюдать их в коде.

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

A Quick Answer

This error occurs when Python expects an indented block and doesn’t find it. For example:

Output:

line 3
print(a)
^
IndentationError: expected an indented block

Solution

The error log shows where the indentation problem is arising from. In the above case, it is in line 3. If we indent that line as shown below, the problem is solved.

Output (no IndentationError):

7

IndentationError can also occur in other circumstances. The rest of the article covers those circumstances and explains the purpose of indentation in Python.

Indentation in Python

Indentation refers to adding white spaces before a code statement. In Python, indentation is used to group code statements into blocks. A programming language that allows code grouping is called a block-structured language – Python is one such language.

A block in a programming/ scripting language is used to limit the lexical scope of a variable, function, or class. In some other cases, however, grouping code statements serve the purpose of improving the readability of the code.

Different programming or scripting languages use different methods of grouping code. For example,

Programming Languages Code Blocking
Basic and Fortran No way of explicitly using block structures
ALGOL, Pascal begin…end
Bourne and Bash Shell if…fi, do…done
C, C++, Perl, Java, and many more { }
Python Indentation
Table 1: Code blocking for different programming languages

As shown in the above table, Python operates on a distinct tenet. Python code is organized using indentation; that is, the indentation of code blocks defines those blocks.

In Python language, indentation is a requirement, not a formatting style. This idea makes Python code naturally more readable.

How indentation is done in Python

All statements with the same distance to the right belong to the same block of code, i.e., the statements within a block line up vertically.

The block ends at a line less indented or at the end of the file. If a block has to be more deeply nested, it is simply indented further to the right (see block 3 in Figure 1 below ).

Figure 1 : Left: The code. Right: Block structures delimited by indentation.

Python expects indentation for code structures like classes, functions, if-statement, while, with, for-loop, and try…except for error handling exceptions.

Note: Indentation, in Python, can be done using white spaces from the space bar or the tab key. An indent must be at least one white space or a tab space. A consistent indentation length must be used for all the code blocks in a file.

The Causes and the Solutions to Python “Expected an Indented Block” Error

IndentationError often happens because of the following three reasons:

Reason 1: Not using Indent when it is needed

This error occurs when Python expects an indented block for a given code statement, but it is not given. For example;

a = 7

for i in range(10):

    if i == a:

        print(f«Number {i} found.»)

Output:

line 4
print(f"Number {i} found.")
^
IndentationError: expected an indented block

In the code snippet above, Python excepts indentation under if-statement, which is shown clearly on the error log.

Solution

Check your code to ensure that you use indentation spaces when needed. In most cases, Python will show you the code line causing the problem. In the above example, we need to indent the print statement in line 4 as follows:

a = 7

for i in range(10):

    if i == a:

        print(f«Number {i} found.»)

Output:

Number 7 found.

Reason 2: using indentation spaces of different sizes

Another form of IndentationError can arise because of using indentation spaces of inconsistent sizes. Here is an example (based on the code editor you are using the error thrown here might match the error explained in the next section):

a = 7

for i in range(10):

    if i == a:

        print(f«Number {i} found.»)

Output:

IndentationError: unindent does not match any outer indentation level

The error produced is caused by using different sizes of indentation space. The block under the for-loop is 2 tabs, whereas the block under the if-statement is 2 tabs and 1 space.

Solution

The code blocks of the same level must be the same distance from the left margin. In the above code, for example, we can solve the problem by using a tab to indent the for-statement as block 1 and 2 tabs to indent block 2 (the if-statement).

Reason 3: Inconsistent use of tabs and spaces in indentation

Python code blocks must be indented using either tabs or white spaces – do not mix the two in one file. This indentation problem might be difficult to identify at a glance because the length of a tab and 4 spaces, for example, might look the same – but they are not. Here is an example,

a = 7

for i in range(10):

    if i == a:

        print(f«Number {i} found.»)

Output:

line 4
TabError: inconsistent use of tabs and spaces in indentation

Python complains about using tabs and spaces in our indentation. For for-loop, I used a single tab, and under if-statement, I used 4 spaces. According to the Python interpreter, that is inconsistent.

Note: Python marks this error as a TabError and not IndentationError.

Solution

Check the problematic line and use an indentation matching what you used in the preceding lines.

To identify the discrepancy, you can search for white space in your code and, in so doing, be able to locate the problematic line(s). For most editors, this can be achieved by opening a search bar with Ctrl+F, hitting the space bar, and then Enter.

Conclusion

Indentation in Python is a language requirement – it is not used to improve the readability of code only. For that reason, indentation must be done correctly; otherwise, Python will throw an error.

In this article, we discussed three reasons that cause the IndentationError – missing indentation, using indent spaces of different sizes, and mixing tabs and spaces for indentation. We also covered the solution to such errors.

Пишу калькулятор вот такая ошибка:

if user_action == 'ВЫЧИТАТЬ' or user_action == 'вычитать' or user_action == 'Вычитать':
     ^
IndentationError: expected an indented block


  • Вопрос задан

    более трёх лет назад

  • 14708 просмотров

У вас либо отсутствует необходимый отступ в этой строке, либо присутствует лишний отступ раньше этой строки.

Пригласить эксперта


  • Показать ещё
    Загружается…

09 июн. 2023, в 01:21

10000 руб./за проект

09 июн. 2023, в 01:06

50000 руб./за проект

09 июн. 2023, в 00:36

1000 руб./за проект

Минуточку внимания

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.

Woman holding a book with the title Python

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:

Spyder interface

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:

A Python function to compute the factorial of an integer

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:

  1. Two indent levels in, aligned with «res =…»
  2. 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.

Понравилась статья? Поделить с друзьями:
  • 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