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

Ошибка expected an indented biock в Python, как исправить?

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

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

print(»)
print(»)
print(‘КАЛЬКУЛЯТОР’)
print(‘Правила исполнения’)
print(‘***___***’)
print(‘Вначале введите 2 числа с которыми будете проводить действия’)
print(‘Введите СЛОЖИТЬ чтобы сложить 2 числа’)
print(‘Введите ВЫЧИТАТЬ чтобы вычесть 2 введённых числа’)
print(‘Введите УМНОЖИТЬ чтобы умножить 2 введённых числа’)
print(‘Введите РАЗДЕЛИТЬ чтобы разделить 2 введённых числа’)
print(‘Введите СТЕПЕНЬ чтобы возвести число в степень’)
print(‘Введите ОСТАТОК чтобы найти остаток от деления’)
print(‘Введите СТОП чтобы завершить программу’)
print(»)
chislo = float(input(‘Введите перввое число: ‘))
chislo1 = float(input(‘Введите второе число: ‘))
user_action = input(‘Введите действие: ‘)

if user_action == ‘СТОП’ or user_action == ‘стоп’ or user_action == ‘Стоп’:
break
if user_action == ‘СЛОЖИТЬ’ or user_action == ‘сложить’ or user_action == ‘Сложить’:

if user_action == ‘ВЫЧИТАТЬ’ or user_action == ‘вычитать’ or user_action == ‘Вычитать’:

if user_action == ‘УМНОЖИТЬ’ or user_action == ‘умножить’ or user_action == ‘Умножить’:

if user_action == ‘РАЗДЕЛИТЬ’ or user_action == ‘разделить’ or user_action == ‘Разделить’:

if user_action == ‘СТЕПЕНЬ’ or user_action == ‘степень’ or user_action == ‘Степень’:

if user_action == ‘ОСТАТОК’ or user_action == ‘остаток’ or user_action == ‘Остаток’:

Источник

Why am I getting «IndentationError: expected an indented block»? [duplicate]

6 Answers 6

As the error message indicates, you have an indentation error. It is probably caused by a mix of tabs and spaces.

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:

The output states that you need to have an indented block on line 4, after the else: statement

Example 2, unindented block:

— You are using Python2.x and have a mix of tabs and spaces:

Please note that before if, there is a tab, and before print there is 8 spaces.

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.

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:

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)

Eventually, to come back on your problem:

Just look at the line number of the error, and fix it using the previous information.

Источник

Я получаю IndentationError. Как это исправить?

у меня есть Python-скрипт:

однако, когда я пытаюсь запустить свой скрипт, Python вызывает IndentationError :

Я продолжал играть со своей программой, и я также смог произвести три другие ошибки:

что означают эти ошибки? Что я делаю не так? Как я могу исправить свой код?

4 ответов

почему отступ имеет значение?

в Python отступ используется для разграничения блоки кода. Это отличается от многих других языков, которые используют фигурные скобки <> для разграничения блоков, таких как Java, Javascript и C. Из-за этого пользователи Python должны уделять пристальное внимание тому, когда и как они отступают от своего кода, потому что имеет значение пробел.

немного истории

использование отступов Python происходит непосредственно из ABC, но эта идея не возникла с ABC-он уже был продвинут Дональдом Кнутом и был хорошо известной концепцией стиля программирования. (Язык программирования occam также использовал его.) Однако авторы ABC изобрели использование двоеточия, которое отделяет предложение о вводе от отступа блока. После раннего тестирования пользователя без двоеточия было обнаружено, что смысл отступа был неясен новичкам, обучаемым первым шагам программирования. Добавление толстой кишки значительно прояснило его: толстая кишка каким-то образом привлекает внимание к тому, что следует, и связывает фразы До и после него вместе в правильном направлении.

как сделать отступ мой код?

основное правило для отступа кода Python (учитывая, что вы рассматриваете всю программу как «базовый блок»): первый оператор в базовом блоке, и каждый последующий оператор после него должен быть отступом на ту же сумму.

так что технически следующие программы правильно:

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

используйте 4 пробела на каждый уровень отступа.

то есть каждое утверждение то есть, начиная новый блок и каждый последующий оператор в новом блоке, должен быть отступом четыре пробела от текущего уровня отступа. Вот выше с отступом по данным руководства стиль PEP8:

можно ли использовать вкладки?

Python понимает, что некоторые люди по-прежнему предпочитают вкладки пробелам и что устаревший код может использовать вкладки, а не пробелы, поэтому он позволяет использовать вкладки в качестве отступов. PEP8 касается этого тема:

пробелы являются предпочтительным методом отступа.

вкладки должны использоваться исключительно для согласования с кодом, который уже имеет отступы с вкладками.

Читайте также:  что делать если в симс 4 не запускается семья

Python 3 запрещает смешивание вкладок и пробелов для отступов.

код Python 2 с отступом со смесью вкладок и пробелов должен быть преобразован в использование исключительно пробелов.

при вызове интерпретатора командной строки Python 2 с параметром-t он выдает предупреждения о коде, который незаконно смешивает вкладки и пробелы. При использовании-tt эти предупреждения становятся ошибками. Эти варианты настоятельно рекомендуется!

что означает» IndentationError: неожиданный отступ»?

эта ошибка возникает, когда оператор имеет излишний отступ или его отступ не совпадает с отступом прежних операторов в том же блоке. Например, первый оператор в программе ниже излишне отступ:

в этом примере can_drive = True строка if блок не соответствует отступу любого предыдущего утверждения:

исправить

исправление этой ошибки заключается в том, чтобы сначала убедиться, что проблемная строка даже должна быть отступом. Например, приведенный выше пример использования print может быть исправлено просто быть unindenting линии:

что означает» IndentationError: ожидаемый отступ блока»?

эта ошибка возникает, когда Python видит ‘заголовок’ для составной оператор, например, if : или while : но тело составного оператора или блок никогда не определяется. Например, в приведенном ниже коде мы начали if утверждение, но мы никогда не определяем тело для утверждения:

в этом втором примере, мы начали писать for цикл, но мы забываем отступ for тело цикла. Поэтому Python по-прежнему ожидает отступом на for петли тело:

комментарии не считаются органы:

исправить

исправление этой ошибки состоит в том, чтобы просто включить тело для составного оператора.

как показано выше, распространенная ошибка новых пользователей является то, что они забывают отступ тела. Если это так, убедитесь, что каждый оператор, предназначенный для включения в тело составного оператора, имеет отступ на том же уровне под началом составного оператора. Здесь является ли приведенный выше пример фиксированным:

Другим распространенным случаем является то, что по какой-то причине пользователь может не захотеть определить фактическое тело для составного оператора или тело может быть прокомментировано. В этом случае pass оператор можно использовать. The pass оператор может использоваться везде, где Python ожидает один или несколько операторов в качестве заполнителя. из документации pass :

вот приведенный выше пример с if оператор исправлен с помощью pass ключевые слова:

что означает «IndentationError: unindent не соответствует никакому внешнему уровню отступа»?

эту ошибку особенно трудно поймать, потому что даже одно пространство приведет к сбою кода.

исправить

исправление состоит в том, чтобы убедиться, что при снятии оператор, уровень отступа соответствует уровню предыдущего оператора. Рассмотрим приведенный выше пример еще раз. В примере я хочу, чтобы второй вызов для печати был в первом if заявления тела. Поэтому мне нужно убедиться, что уровень отступа этой строки соответствует уровню предыдущих утверждений в первом инструкции:

я все еще получаю IndentationError, но моя программа, похоже, правильно отступ. Что мне делать?

если ваш программа визуально имеет правильный отступ, но вы все равно получаете IndentationError у вас, скорее всего,смешанные вкладки с пробелами. Это иногда вызывает Python вызывает странные ошибки. См. подраздел особых случаях под что означает» TabError: непоследовательное использование вкладок и пробелов в отступах»? для более глубокого разъяснения проблемы.

что делает » TabError: непоследовательное использование вкладок и пробелов в отступах» означает?

эта ошибка возникает только при попытке смешать вкладки и пробелы в качестве символов отступа. Как сказано выше, Python не позволит вашей программе содержать сочетание вкладок и пробелов и вызовет конкретное исключение TabError если он найдет, что у вас есть. Например, в приведенной ниже программе для отступов используется сочетание вкладок и пробелов:

здесь изображение, которое визуально показывает пробелы в вышеуказанной программе. Серые точки-это пробелы, а серые стрелки-вкладки:

мы действительно смешанные пробелы и знаки табуляции для отступов.

особых случаях

Обратите Внимание На Python не будет всегда поднять TabError если вы смешиваете вкладки и пробелы в своей программе. Если отступ программы однозначно, Python позволит смешивать вкладки и пробелы. Например:

и иногда Python просто задыхается от смеси вкладок и пробелов и ошибочно поднимает IndentationError исключение, когда TabError было бы более уместно. Другой пример:

как вы можете видеть, запуск вашего кода таким образом может создать таинственные ошибки. Хотя программа визуально кажется, все в порядке, Python запутался, пытаясь разобрать вкладки и пробелы, используемые для отступов и ошибок.

исправить

если ваша программа короткая, вероятно, самым простым и быстрым решением является просто повторный отступ программы. Убедитесь, что каждый оператор отступается четырьмя пробелами на уровень отступа (см. как я отступ мой код?).

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

многие редакторы, такие как PyCharm и SublimeText есть опции для автоматического преобразования вкладок в пробелы. Есть также несколько он-лайн инструментов, таких как Вкладки В Пробелы или Browserling это позволяет быстро изменить отступ кода. Есть также инструменты, написанные на Python. autopep8 например, может автоматически повторно отступать ваш код и другие ошибки отступа, а также.

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

записку о «SyntaxError» связанные проблемы отступа

хотя и не часто, иногда некоторые SyntaxError исключения возникают из-за неправильного отступа. Например, посмотрите на код ниже:

при выполнении вышеуказанного кода a SyntaxError is raised :

исправить этот тип ошибки-просто правильно изменить отступ вашего кода. Чтобы узнать, как правильно отступить код, см. раздел как сделать отступ мой код?.

мне все еще трудно с синтаксисом отступов Python. Что мне делать?

не расстраивайтесь, если вы все еще боретесь. Он может потребоваться время, чтобы привыкнуть к Правила синтаксиса пробелов Python. Вот несколько советов, которые помогут:

Читайте также:  различие между нынешним и предшествующим состоянием какого либо аспекта социальной структуры

ресурсы используется

Возвышенный Текст 3

если случится, что вы кодируете в Sublime Text 3, это может помочь вам с отступами problemes

в Sublime Text при редактировании файла Python:

возвышенное текстовое меню>предпочтения>Настройки Используется Специальный Синтаксис :

Python.sublime-настройки

вы видите, у вас есть небольшая ошибка.

вы должны были делать:

Как вы можете видеть, ваша печать имеет только отступ 3 пробела, она должна быть отступом 4 пробела.

быстрое исправление для пользователей Sublime:

Источник

[Solved] IndentationError: Expected An Indented Block Error

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.

What is IndentationError: Expected an indented block?

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:

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.

Output:

Explanation:

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.

Output:

Explanation:

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.

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.

Output:

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

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:

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.

Output:

Explanation:

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.

Output:

Explanation:

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

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:

3. Pycharm

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

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

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.

Источник

How to Solve Python expected an indented block Error

Not all programming languages are measured on the Indentation, but Python is a different language. Python uses indentation to decide which lines of code belong to other lines. Indentation uses spaces or tabs to separate the code for better visualization.

If the code is not indented correctly, you will face this IndentationError: expected an indented block. In Python, Indentation is part of the syntax. Let’s see how to resolve the Indentation error.

Python expected an indented block.

To resolve expected an indented block in Python, correct the indentation of each block. Before Python runs any code in your program, it will first discover the correct parent and children of each line. Python throws an Indentation whenever it comes across a line for which it cannot define the right parent to assign.

See the following example where Python throws an IndentationError.

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

To resolve this error, check if you have left alone an elif: part of an if-condition, and check if the indentation is missing after conditions, loops, etc.

You can see in our example that after if block, elif block, and else block, there should be an indentation before starting a new statement. Still, we did not put any whitespace, and that causes an indentation error. Let’s resolve the error by providing whitespaces.

Output

And the IndentationError is successfully resolved.

For example, Python statements that start with def or if 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.

Output

After Python reads the if statement, it expects to see at least one child line following it. However, since the next non-empty line it reads is the elif statement which means the if statement has no children, and 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.

Now, 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.

Источник

Сказочный портал