Unexpected 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.

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.

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

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

Понравилась статья? Поделить с друзьями:
  • Unknown file version fortniteclient win64 shipping exe ошибка
  • Unknown device ошибка 43 как исправить windows 7
  • Unetbootin ошибка ubnldr mbr
  • Unknown device код 43 как исправить ошибку usb
  • Unetbootin выдает ошибку