Expected an indented block python ошибка что значит

Отступы в Python строгие. Очень важно соблюдать их в коде. Если неправильно организовать отступы, пробелы или табуляции в программе, то вернется ошибка

Отступы в 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

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.

Like other programming languages Python also follow a strict syntax to write the code. In Python, we do not have the curly brackets to represent the block code. Instead, we use the indentation. This indentation syntax is mandatory and provides a better and legible way to write code in Python. While writing the block code body in Python, if we do not indent the code properly, there we would receive the »

IndentationError: expected an indented block

» error.

This Python guide will walk you through Python’s

IndentationError: expected an indented block

in detail. This article also covers some common example scenarios that show how to debug a Python program error. So let’s get started with the Error statement.

In other programming languages like C, C++, Java, and JavaScript, we only use indentation for code legibility, and there we have curly brackets to represent block code for functions, if..else, class, etc., body. In Python, we use indentation when we want to write the body or block code for functions, if..else, and class statements. And there, if we do not intend the code properly, we will encounter the error «IndentationError: expected an indented block». This error statement has two sub statements

  1. IndentationError
  2. expected an indented block


1. IndentationError

IndentationError is one of the Python exceptions, it is raised by the Python interpreter when we do not indent the code for a block statement.


2. expected an indented block

This statement is the error message, telling us that we have not properly indented the block code body.


error example

def total(bill):
return sum(bill)

bill = [282, 393, 3834, 888, 9373,767]

print("Total is:", total(bill))


Output

 File "main.py", line 2
return sum(bill)
^
IndentationError: expected an indented block


Break the code

In the first line of our code, we have defined a function using the

def

keyword, and in the second line, we have the return statement that is not indented for the

total(bill)

function definition. That’s why Python is throwing the

IndentationError: expected an indented block

error. Even in the error output statement, Python is showing the error message that

return sum(bill)

is expected to indent for the function body.


Solution

To solve the above problem, we need to indent the return statement inside the function body.

def total(bill):
    return sum(bill)

bill = [282, 393, 3834, 888, 9373,767]

print("Total is:", total(bill))


Output

Total is: 15537


Common Example Scenario

We only receive this error in our program when we do not indent a single line of code for the block code statements.


Error Example

Suppose we have a list of numbers, and we need to write a function that accepts that list and returns two lists, even and odd. Where even contain only even numbers, and the old list contains odd numbers from the numbers list.

def even_odd(numbers):
    odd = list()
    even = list()
    
    for num in numbers:
        #check for the odd and even numbers
    if num%2==0:  #error
        even.append(num)
    else:
        odd.append(num)

    return even, odd

numbers = [97, 60, 33, 39, 54, 87, 27, 99, 32, 94, 69, 42, 83, 20, 36, 34, 62]

even, odd = even_odd(numbers)

print("ODD:", odd)
print("EVEN:", even)


Output

  File "main.py", line 7
    if num%2==0:
    ^
IndentationError: expected an indented block


Break the Error

In this example, we are receiving the error in line 7 with the

if num%2==0:

statement, which you can also see in the output. In the above program, we have not indented any code for the

for

loop that’s why we are getting the error. And the error output statement shows us that the if num%2==0: is expected to be indented for that

for

loop.


Solution

To solve the above problem, all we need to do is indent the if logic code for the

for

loop statement so that the logic can iterate multiple times.

def even_odd(numbers):
    odd = list()
    even = list()
    
    for num in numbers:
        #check for the odd and even numbers
        if num%2==0: 
            even.append(num)
        else:
            odd.append(num)

    return even, odd

numbers = [97, 60, 33, 39, 54, 87, 27, 99, 32, 94, 69, 42, 83, 20, 36, 34, 62]

even, odd = even_odd(numbers)

print("ODD:", odd)
print("EVEN:", even)


Output

ODD: [97, 33, 39, 87, 27, 99, 69, 83]
EVEN: [60, 54, 32, 94, 42, 20, 36, 34, 62]

With this, now our code runs successfully.


Conclusion

The IndentationError: expected an indented block is a very common error. If you are using an advanced Python IDE or text editor, there you get the auto-indentation feature that minimizes this error. Still, if you are getting this error in your output, all you need to do is go for the error line and check if the block code is properly indented or not. Now you know how to solve this error for your Python program.

If you are still stuck in this error, please share your code and query in the comment section. We will try to help you in debugging.


People are also reading:

  • Python TypeError: slice indices must be integers or None or have an __index__ method Solution

  • Reading and writing CSV files in Python

  • Python TypeError: ‘float’ object is not subscriptable Solution

  • Copy file and directory using shutil in Python

  • Python valueerror: too many values to unpack (expected 2) Solution

  • How to extract all stored chrome password with Python?

  • Python local variable referenced before assignment Solution

  • How to automate login using selenium in Python?

  • Python AttributeError: ‘numpy.ndarray’ object has no attribute ‘append’ Solution

  • Counter in collections with example in Python

Понравилась статья? Поделить с друзьями:
  • Exiting due to fatal error openvpn windows 7
  • Exit with code 1 due to network error contentnotfounderror
  • Exit status 1 ошибка компиляции для платы generic esp8266 module
  • Exit status 1 ошибка компиляции для платы esp32 dev module
  • Exit status 1 ошибка компиляции для платы arduino nano что делать