Программа не работает. Что делать?
Моя программа не работает! Что делать? В данной статье я постараюсь собрать наиболее частые ошибки начинающих программировать на python 3, а также расскажу, как их исправлять.
Проблема: Моя программа не запускается. На доли секунды появляется чёрное окошко, а затем исчезает.
Причина: после окончания выполнения программы (после выполнения всего кода или при возникновении исключения программа закрывается. И если вы её вызвали двойным кликом по иконке (а вы, скорее всего, вызвали её именно так), то она закроется вместе с окошком, в котором находится вывод программы.
Решение: запускать программу через IDLE или через консоль.
Проблема: Не работает функция input. Пишет SyntaxError.
Причина: Вы запустили Python 2.
Проблема: Где-то увидел простую программу, а она не работает.
Причина: Вам подсунули программу на Python 2.
Решение: Прочитать об отличиях Python 2 от Python 3. Переписать её на Python 3. Например, данная программа на Python 3 будет выглядеть так:
Проблема: TypeError: Can’t convert ‘int’ object to str implicitly.
Причина: Нельзя складывать строку с числом.
Решение: Привести строку к числу с помощью функции int(). Кстати, заметьте, что функция input() всегда возвращает строку!
Проблема: SyntaxError: invalid syntax.
Причина: Забыто двоеточие.
Проблема: SyntaxError: invalid syntax.
Причина: Забыто равно.
Проблема: NameError: name ‘a’ is not defined.
Причина: Переменная «a» не существует. Возможно, вы опечатались в названии или забыли инициализировать её.
Решение: Исправить опечатку.
Проблема: IndentationError: expected an indented block.
Причина: Нужен отступ.
Проблема: TabError: inconsistent use of tabs and spaces in indentation.
Причина: Смешение пробелов и табуляции в отступах.
Решение: Исправить отступы.
Проблема: UnboundLocalError: local variable ‘a’ referenced before assignment.
Причина: Попытка обратиться к локальной переменной, которая ещё не создана.
Проблема: Программа выполнилась, но в файл ничего не записалось / записалось не всё.
Причина: Не закрыт файл, часть данных могла остаться в буфере.
Проблема: Здесь может быть ваша проблема. Комментарии чуть ниже 🙂
IndentationError: expected an indented block
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.
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
Solution
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
Output
Solution
Output
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
Solution
Output
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
Output
Solution
Output
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
Example
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.
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: expected an indented block
выдаёт ошибку на второй строке.
Знаю что эта ошибка связанная с стандартами РЕР, грубо говоря с отступами и тд, однако все отступы на месте по 4 проблема, смешки табуляции и пробелов нет.
* это кусок кода, весь код отправить не могу *
В чем проблема, если не в отступах?
IndentationError: expected an indented block
В чем ошибка print f.read() SyntaxError: invalid syntax os.chdir(INSTALLER_HOME) пишет.
expected an indented block
Начал изучать python все делал как написано на сайте и выдает ошибку
Где ошибка: expected an indented block?
name = input(«Как я могу к вам обращаться? «) print(«Здравствуй, «, name) age =.
Найти причину ошибки «expected an indented block»
Начал изучать python все делал как написано на сайте Правила форума п.5.19 Потрудитесь свой код.
не грубо, а точно, интерпретатор не ошибается
удаляй отступы и пиши их заново пробелами.
зачем такая вложенность ифов? пробуй упрощать и разбивать на функции
ХЗКАКОЕИМЯ, так это не код, это что-то несусветное, разве это вообще хоть как то работало?
нигде не используется
Добавлено через 1 минуту
Меня больше смущает, что такая ошибка была у всех, но из за отступов, а у меня с отступами все вроде как хорошо, кстати, если Ты не найдешь причину ошибки, то Ты снимаешь шляпу
Добавлено через 1 минуту
ХЗКАКОЕИМЯ, я такое не могу запустить из-за горы твоих ошибок, так что не надо. Мне ИДЕ показывает не интендаейшн ошибку и вообще видимо ты не весь код прислал, а я просил файлом. Для чистоты давай весь код и чтобы там не падало из-за того что написано none или нет тела в условии.
А то тема про отступы а там каша
Добавлено через 2 минуты
возможно еще местная форма ввода поправила пробелы, потому что проблемы нет с отступами
Ошибка expected an intended block
Сама задача звучит так: даны два круга с общим центром и радиусами R1 и R2 (R1 > R2). Найти площади.

Ошибка: File «D:\ъ\bot.py», line 5 if message.text == «/start» : ^ IndentationError.
IndentationError: expected an indented block
Я еще новичок по питоне и человек я творческий нежели программист, и пишу код который нам дают на.
IndentationError: expected an indented block и еще по мелочи =)
Доброго дня, криптеры) вернее ночи.. Я новичок в пайтоне (пока), раньше начинал изучать.
Oracle Forms: Master block, detail block
Имеется Master block и detail block. Из канвы Master хочу дать возможность 1) вызвать канву detail.
[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.














