Меню

Syntaxerror unexpected indent python ошибка

Содержание

  1. IndentationError: unexpected indent
  2. What are the reasons for IndentationError: unexpected indent?
  3. Python and PEP 8 Guidelines
  4. Solving IndentationError: expected an indented block
  5. Example 1 – Indenting inside a function
  6. Example 2 – Indentation inside for, while loops and if statement
  7. Conclusion
  8. IndentationError: unexpected indent
  9. Exception
  10. Root Cause
  11. Solution 1
  12. Program
  13. Output
  14. Solution
  15. Output
  16. Solution 2
  17. Program
  18. Solution
  19. Solution 3
  20. Solution 4
  21. Command
  22. Example
  23. Solution 5
  24. 10 ошибок и исключений, с которыми часто сталкиваются новички в Python
  25. IndentationError: Unexpected Unindent in Python
  26. How to Solve IndentationError: unexpected indent in Python
  27. How to Solve IndentationError: unexpected indent error in Python
  28. How to Solve IndentationError: unindent does not match any outer indentation level in Python
  29. How to Solve IndentationError: unexpected unindent in Python

IndentationError: unexpected indent

Table of Contents Hide

Python language emphasizes indentation rather than using curly braces like other programming languages. So indentation matters in Python, as it gives the structure of your code blocks, and if you do not follow it while coding, you will get an indentationerror: unexpected indent.

What are the reasons for IndentationError: unexpected indent?

IndentationError: unexpected indent mainly occurs if you use inconsistent indentation while coding. There are set of guidelines you need to follow while programming in Python. Let’s look at few basic guidelines w.r.t indentation.

Python and PEP 8 Guidelines

  1. Generally, in Python, you follow the four spaces rule according to PEP 8 standards.
  2. Spaces are the preferred indentation method. Tabs should be used solely to remain consistent with code that is already indented with tabs.
  3. Do not mix tabs and spaces. Python disallows the mixing of indentation.
  4. Avoid trailing whitespaces anywhere because it’s usually invisible and it causes confusion.

Solving IndentationError: expected an indented block

Now that we know what indentation is and the guidelines to be followed, Let’s look at few indentation error examples and solutions.

Example 1 – Indenting inside a function

Lines inside a function should be indented one level more than the “def functionname”.

Correct way of indentation while creating a function.

Example 2 – Indentation inside for, while loops and if statement

Lines inside a for, if, and while statements should be indented more than the line, it begins the statement so that Python will know when you are inside the loop and when you exit the loop.

Suppose you look at the below example inside the if statement; the lines are not indented properly. The print statement is at the same level as the if statement, and hence the IndentationError.

To fix the issues inside the loops and statements, make sure you add four whitespaces and then write the lines of code. Also do not mix the white space and tabs these will always lead to an error.

Conclusion

The best way to avoid these issues is to always use a consistent number of spaces when you indent a subblock and ideally use a good IDE that solves the problem for you.

Источник

IndentationError: unexpected indent

The IndentationError: Unexpected indent error indicates that you have added an excess indent in the line that the python interpreter unexpected to have. An unexpected indent in the Python code causes this indentation error. To overcome the Indentation error, ensure that the code is consistently indented and that there are no unexpected indentations in the code. This would fix the IndentationError: Unexpected indent error.

The IndentationError: Unexpected indent error occurs when you use too many indent at the beginning of the line. Make sure your code is indented consistently and that there are no unexpected indent in the code to resolve Indentation error. Python doesn’t have curly braces or keyword delimiter to differentiate the code blocks. In python, the compound statement and functions requires the indent to be distinguished from other lines. The unexpected indent in python causes IndentationError: Unexpected indent error.

The indent is known as the distance or number of empty spaces between the start of the line and the left margin of the line. Indents are not considered in the most recent programming languages such as java, c++, dot net, etc. Python uses the indent to distinguish compound statements and user defined functions from other lines.

Exception

The error message IndentationError: Unexpected indent indicates that there is an excess indent in the line that the python interpreter unexpected to have. The indentation error will be thrown as below.

Root Cause

The root cause of the error message “IndentationError: Unexpected indent” is that you have added an excess indent in the line that the python interpreter unexpected to have. In order to resolve this error message, the unexpected indent in the code, such as compound statement, user defined functions, etc. must be removed.

Solution 1

The unexpected indent in the code must be removed. Walk through the code to trace the indent. If any unwanted indent is found, remove it. The lines inside blocks such as compound statements and user defined functions will normally have excess indents, spaces, tabs. This error “IndentationError: unexpected indent” is resolved if the excess indents, tabs, and spaces are removed from the code.

Program

Output

Solution

Output

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

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 4

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 5

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.

Источник

10 ошибок и исключений, с которыми часто сталкиваются новички в Python

“Пожалуйста, помогите понять, что змеюка от меня хочет”

Такое сообщение мне однажды написал студент, и это хороший эпиграф для этой статьи.
Давайте посмотрим на 10 наиболее частых сообщений об ошибках, которые встречаются на профессиональном пути питониста и разберёмся, как можно исправить код в этих ситуациях.
В Python можно выделить два различных типа ошибок: синтаксические ошибки и исключения. Синтаксические ошибки (их ещё называют ошибками парсинга) возникают ещё до выполнения кода на этапе синтаксического анализа. Эти ошибки особенно часто встречаются на первом этапе знакомства с Python. Они рассмотрены в пунктах 1–2 списка. Остальные пункты — про исключения. Исключения обнаруживаются уже во время выполнения программы, их мы можем поймать и обработать (это тема одной из следующих статей).

“Синтаксическая ошибка — неверное отображение совокупности установленных для данной языковой группы правил языка, относящихся к построению лексических единиц — словосочетаний и предложений.”

То есть это ошибки именно в написании.

IndentationError: unexpected indent — ошибка с отступом, одна из первых, которую встречают новички.
Моя самая первая рабочая задача на Python была написать скрипт, который разбирает файл и записывает данные в таблицы БД. Звучит серьезно, но у меня был пример скрипта, который я могу немного изменить и всё заработает. Так я наивно подумала. Я провела полдня в битве с вот такими ошибками. Тогда я ещё не знала как много значат отступы в Python.
В Python отступы это важно. Здесь, в отличие от многих других языков программирования, не используются скобки или ключевые слова для обозначения границ блоков кода. Блоки кода (конструкции if-else, for, while, try-except, функции и т.д.) определяются отступами. Увеличение отступа означает начало блока, уменьшение — конец блока. Для отступов используется 4 пробела или табуляция, смешивание символов табуляции и пробелов недопустимо. Советую всегда использовать 4 пробела, как это рекомендуется в PEP8.

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

2. SyntaxError
Причины тут могут быть самыми разными . Например, пропуск закрывающей скобки или кавычки.
У нас есть простая программа, которая запрашивает у пользователя возраст и выводит его на экран. Что будет, если мы забудем закрывающую кавычку — EOL while scanning string literal

Если поставим в начале строки одинарную кавычку, а закроем двойной или наоборот, то получим аналогичную ошибку, по своей сути они одинаковые — считается что у строки нет завершающей кавычки.

А если забудем про скобку, то увидим такое сообщение — SyntaxError: invalid syntax

Аналогично и с двоеточием: строка с if должна завершиться двоеточием, если нет, то увидим такую же ошибку

А если запутаемся в скобках и поставим закрывающую не такую как открывающую, например ( и ], то получим такой вид синтаксической ошибки: closing parenthesis ‘]’ does not match opening parenthesis ‘(‘

Решение: устранить синтаксические ошибки, внимательно посмотреть в сообщении на указанную строку и на строку выше и постараться найти причину.

Исключения возникают во время выполнения кода и могут быть обработаны с помощью конструкции try-except ( подробнее об этом будет рассказано в следующих статьях, пока в качестве решения предлагаются альтернативные варианты).

3. TypeError
Такое исключение возникает, если мы хотим применить операцию, недопустимую для какого-нибудь типа. Посмотрим на код, который должен получить число и возвести его в квадрат.

Получаем ошибку, тип переменной age — это строка, а строку невозможно возвести в квадрат, это математическая операция, которая может быть применена к числам.

Решение: использовать операции приведения типов (в данном случае поможет int(age)), использовать только операции допустимые для данного типа.

4. ValueError
Ошибку ValueError: invalid literal for int() with base 10: мы можем увидеть, например, если попытаемся привести к типу int значение, которое нельзя сделать числом. Пример:

Решение: проверим получится ли преобразовать строку к числу

Также ValueError можно поймать в таком виде list.remove(x): x not in list если попытаться удалить из списка число, которого там нет:

Решение: перед удалением проверять, что элемент есть в списке

5. NameError
Если сделать опечатку в имени переменной (или функции) или забыть определить переменную, то получим исключение NameError: name ‘…’ is not defined.

Аналогичная ситуация возникает и при использовании не того регистра в именах. Обратите внимание, что для Python Age и age это разные имена.

Решение: проверить корректность написания имен переменных, убедиться, что все используемые переменные были объявлены

6. IndexError
При обращении к элементу массива по несуществующему индексу возникает исключение IndexError: list index out of range

Если мы применим метод pop к несуществующему индексу, то текст немного изменится IndexError: pop index out of range

Решение: у нас есть список a, его длина — это len(a); помним, что максимальный индекс для списка a в положительной нотации будет len(a)-1, а в отрицательной -len(a).

7. KeyError
Возникает при попытке обратиться к словарю по несуществующему ключу.
У нас есть словарь summer с именами летних месяцев и количеством дней в них и май выдался настолько теплым, что мы перепутали его с летним месяцем и решили поискать его длину в словаре summer. Вот что получилось:

Решение: использовать метод get, который защитит нас от такой ошибки

Или проверять существование ключа в словаре до обращения к нему:

8. AttributeError
Исключение AttributeError: ‘…’ object has no attribute ‘…’ появляется при попытке вызвать метод, которого нет для этого типа данных.
Возьмем список и попробуем посчитать его сумму таким образом:

Решение: проверять наличие метода по документации или с помощью функции help

Выяснили с помощью help, что у списка нет метода sum, посмотрим справку по sum:

Такая фукнция есть, ей и воспользуемся:

9. ModuleNotFoundError
ModuleNotFoundError: No module named ‘…’ можно увидеть при импорте модуля, который ещё не установлен у нас.
Допустим, у нас есть очень долгий цикл и мы захотели видеть прогресс его выполнения. Мы нагуглили модуль tqdm и решили им воспользоваться, но если мы забыли предварительно этот модуль установить, то получим такой результат:

Решение: установим модуль с помощью pip install tqdm и опять запустим свой код

10. FileNotFoundError
Если попытаться открыть файл, которого нет, то Python нам так об этом и скажет FileNotFoundError: [Errno 2] No such file or directory

Решение: добавим файл в нужную директорию

Не бойтесь ошибок и сообщений об ошибках. Не ошибается только тот, кто ничего не делает. Практикуйтесь в написании кода и анализе ошибок.

Источник

IndentationError: Unexpected Unindent in Python

Python indentation is a part of the syntax. It’s not just for decoration.

You’ll learn what these errors mean and how to solve them:

  • IndentationError: unexpected indent
  • IndentationError: expected an indented block
  • IndentationError: unindent does not match any outer indentation level
  • IndentationError: unexpected unindent

So if you want to learn how to solve those errors, then you’re in the right place.

Let’s kick things off with error #1!

How to Solve IndentationError: unexpected indent in Python

Python is a beautiful language. One of the key features of this beauty is the lack of curly braces and other symbols that mark the beginning and end of each block.

Even in C it is considered a good practice to indent, denoting different levels in the code. Compare the same C ++ code with and without indentation. First with the indentation:

And the same code without indentation:

Both codes will compile and run, but the indented code is a lot easier to read. In the second case, it isn’t clear which parenthesis goes with which.

In Python, parentheses aren’t needed, but indentation is. This is what the C++ program would look like in Python:

However, there is a downside to this beauty. If you make a mistake in the indentation, the program will be inconsistent, which will lead to errors when it’s running.

Perhaps, this is a better option than changing the indentation and not getting the error, but changing the meaning of the program.

The error IndentationError: unexpected indent is one that results from wrong indentation. It happens when there are no keywords in front of the indentation. Here’s an example:

Python expects a keyword line to come before an indented line. List of keywords followed by an indented line:

  • class: class definition
  • def: function definition
  • for: a loop with a parameter
  • while: a loop with a condition
  • if, elif, else: conditional operator
  • try, except, finally: exception handling
  • with: a context operator

Python warns you if it finds a line that’s indented, but the previous line doesn’t have these keywords.

How to Solve IndentationError: unexpected indent error in Python

You’ll get a similar error if you don’t indent after a keyword, here’s an example:

IndentationError: expected an indented block happens when you start a construct that assumes you have at least one indented block, but you didn’t indent this.

This is an easy fix. Just indent a block that’s inside a loop or other appropriate construction.

Python uses spaces for indentation, and tabs are automatically converted to four spaces in Python 3 editors.

Another feature is that the number of indent spaces can be any, but inside the block they’re the same.

Since using different numbers of indentations can be confusing, PEP8 recommends exactly four spaces per level of indentation:

This code is possible, it won’t cause an error, but it’ll make your code look terrible to people who’ll read it later.

Often, the IndentationError: unexpected indent error shows up when copying code from any source.

This is a reason why you shouldn’t mindlessly copy-paste code from somewhere.When you borrow code, it’s always best to retype it.

So there won’t be as many errors when you run this code later. And you better understand what you copied.

Even in your very first program, you can get this error if you copy the code along with the layout characters:

Another copying error can happen when you edit your code in a text editor without the ability to replace tabs with 4 spaces, such as Notepad++, and use both tabs and spaces for indentation.

This error is the hardest to figure out because it looks like the code’s on the same line.

The first line has a tab and the second has 4 spaces, which is an entirely different level of indentation for a Python interpreter:

For this error, you can either remove or replace all of the indents, or enable service characters, in Notepad++ this looks like this:

Now you can just replace the tabs with spaces.

How to Solve IndentationError: unindent does not match any outer indentation level in Python

Another error that happens when copying code or when your attention wanders is IndentationError: unindent does not match any outer indentation level. Let’s look at some code that causes such an error:

Draw vertical lines along the indentation levels. We have three indentation levels here: –

  • Original (no indentation)
  • First level is the block inside the loop
  • Second level is the block inside the conditional statement

When the lines are drawn, it becomes obvious that the indentation is not in line with the print statement. This line doesn’t belong to any of the existing indentation levels.

You need one more space, then the code will run:

One way to get around this kind of error is to use automatic code formatters based on PEP8 standards, like autopep8 or Black.

These projects are not primarily intended to fix bugs, but to bring the code up to PEP8 standard, and to maintain code consistency in the project.

When you start out with Python, it is helpful to use these utilities to make beautiful code. But you shouldn’t just do this carelessly. Pay attention to the inaccuracies that such utilities fix.

How to Solve IndentationError: unexpected unindent in Python

A much rarer error is IndentationError: unexpected unindent. Using the try-except operator causes it only under certain conditions.

If you write try, you have to include the except keyword. But if you have just a try without an except, you get SyntaxError: invalid syntax:

But you’ll get an IndentationError: unexpected unindent if you try to use try-except inside a function, loop, condition, or context.

The Python interpreter walks through the code and finds the try keyword, and searches down the except keyword lines at the same indentation level.

If it doesn’t find it, then it means the try-except operator hasn’t finished yet. Until the whole thing’s done, a line with a lower indentation level cannot appear. Here’s an example:

This error is much less common and harder to find. Try must always have at least one except. If you don’t need to do anything on an exception, use the pass keyword.

This isn’t great, but it is syntactically correct.

Use accurate error definitions in your try-except statements, and don’t use empty excepts. If you’re trying to handle an exception, use at least BaseException.

Источник

IndentationErrors serve two purposes: they help make your code more readable and ensure the Python interpreter correctly understands your code. If you add in an additional space or tab where one is not needed, you’ll encounter an “IndentationError: unexpected indent” error.

In this guide, we discuss what this error means and why it is raised. We’ll walk through an example of this error so you can figure out how you can fix it in your program.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

IndentationError: unexpected indent

An indent is a specific number of spaces or tabs denoting that a line of code is part of a particular code block. Consider the following program:

def hello_world():
	print("Hello, world!")

We have defined a single function: hello_world(). This function contains a print statement. To indicate to Python this line of code is part of our function, we have indented it.

You can indent code using spaces or tabs, depending on your preference. You should only indent code if that code should be part of another code block. This includes when you write code in:

  • An “if…else” statement
  • A “try…except” statement
  • A “for” loop
  • A “function” statement

Python code must be indented consistently if it appears in a special statement. Python enforces indentation strictly.

Some programming languages like JavaScript do not enforce indentation strictly because they use curly braces to denote blocks of code. Python does not have this feature, so the language depends heavily on indentation.

The cause of the “IndentationError: unexpected indent” error is indenting your code too far, or using too many tabs and spaces to indent a line of code.

The other indentation errors you may encounter are:

  • Unindent does not match any other indentation level
  • Expected an indented block

An Example Scenario

We’re going to build a program that loops through a list of purchases that a user has made and prints out all of those that are greater than $25.00 to the console.

To start, let’s define a list of purchases:

 purchases = [25.50, 29.90, 2.40, 57.60, 24.90, 1.55]

Next, we define a function to loop through our list of purchases and print the ones worth over $25 to the console:

def show_high_purchases(purchases):
	   for p in purchases:
		        if p > 25.00:
			            print("Purchase: ")
				                print(p)

The show_high_purchases() function accepts one argument: the list of purchases through which the function will search. The function iterates through this list and uses an if statement to check if each purchase is worth more than $25.00.

If a purchase is greater than $25.00, the statement Purchase: is printed to the console. Then, the price of that purchase is printed to the console. Otherwise, nothing happens.

Before we run our code, call our function and pass our list of purchases as a parameter:

show_high_purchases(purchases)

Let’s run our code and see what happens:

  File "main.py", line 7
	print(p)
	^
IndentationError: unexpected indent

Our code does not run successfully.

The Solution

As with any Python error, we should read the full error message to see what is going on. The problem appears to be on line 7, which is where we print the value of a purchase.

	if p > 25.00:
			print("Purchase: ")
				    print(p)

We have incidentally indented the second print() statement. This causes an error because our second print() statement is not part of another block of code. It is still part of our if statement.

To solve this error, we need to make sure that we consistently indent all our print() statements:

	if p > 25.00:
			print("Purchase: ")
			print(p)

Both print() statements should use the same level of indentation because they are part of the same if statement. We’ve made this revision above.

Let’s try to run our code:

Purchase:
25.5
Purchase:
29.9
Purchase:
57.6

Our code successfully prints out all the purchases worth more than $25.00 to the console.

Conclusion

“IndentationError: unexpected indent” is raised when you indent a line of code too many times. To solve this error, make sure all of your code uses consistent indentation and that there are no unnecessary indents.

Now you’re ready to fix this error like a Python expert!

The IndentationError: Unexpected indent error indicates that you have added an excess indent in the line that the python interpreter unexpected to have. An unexpected indent in the Python code causes this indentation error. To overcome the Indentation error, ensure that the code is consistently indented and that there are no unexpected indentations in the code. This would fix the IndentationError: Unexpected indent error.

The IndentationError: Unexpected indent error occurs when you use too many indent at the beginning of the line. Make sure your code is indented consistently and that there are no unexpected indent in the code to resolve Indentation error. Python doesn’t have curly braces or keyword delimiter to differentiate the code blocks. In python, the compound statement and functions requires the indent to be distinguished from other lines. The unexpected indent in python causes IndentationError: Unexpected indent error.

The indent is known as the distance or number of empty spaces between the start of the line and the left margin of the line. Indents are not considered in the most recent programming languages such as java, c++, dot net, etc. Python uses the indent to distinguish compound statements and user defined functions from other lines.

Exception

The error message IndentationError: Unexpected indent indicates that there is an excess indent in the line that the python interpreter unexpected to have. The indentation error will be thrown as below.

 File "/Users/python/Desktop/test.py", line 2
    print "end of program";
    ^
IndentationError: unexpected indent

Root Cause

The root cause of the error message “IndentationError: Unexpected indent” is that you have added an excess indent in the line that the python interpreter unexpected to have. In order to resolve this error message, the unexpected indent in the code, such as compound statement, user defined functions, etc. must be removed.

Solution 1

The unexpected indent in the code must be removed. Walk through the code to trace the indent. If any unwanted indent is found, remove it. The lines inside blocks such as compound statements and user defined functions will normally have excess indents, spaces, tabs. This error “IndentationError: unexpected indent” is resolved if the excess indents, tabs, and spaces are removed from the code.

Program

print "a is greater";
	print "end of program";

Output

 File "/Users/python/Desktop/test.py", line 2
    print "end of program";
    ^
IndentationError: unexpected indent

Solution

print "a is greater";
print "end of program";

Output

a is greater
end of program
[Finished in 0.0s]

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

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 4

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 5

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
Table of Contents
Hide
  1. What are the reasons for IndentationError: unexpected indent?
    1. Python and PEP 8 Guidelines 
  2. Solving IndentationError: expected an indented block
  3. Example 1 – Indenting inside a function
  4. Example 2 – Indentation inside for, while loops and if statement
  5. Conclusion

Python language emphasizes indentation rather than using curly braces like other programming languages. So indentation matters in Python, as it gives the structure of your code blocks, and if you do not follow it while coding, you will get an indentationerror: unexpected indent.

What are the reasons for IndentationError: unexpected indent?

IndentationError: unexpected indent mainly occurs if you use inconsistent indentation while coding. There are set of guidelines you need to follow while programming in Python. Let’s look at few basic guidelines w.r.t indentation.

Python and PEP 8 Guidelines 

  1. Generally, in Python, you follow the four spaces rule according to PEP 8 standards
  2. Spaces are the preferred indentation method. Tabs should be used solely to remain consistent with code that is already indented with tabs.
  3. Do not mix tabs and spaces. Python disallows the mixing of indentation.
  4. Avoid trailing whitespaces anywhere because it’s usually invisible and it causes confusion.

Solving IndentationError: expected an indented block

Now that we know what indentation is and the guidelines to be followed, Let’s look at few indentation error examples and solutions.

Example 1 – Indenting inside a function

Lines inside a function should be indented one level more than the “def functionname”. 

# Bad indentation inside a function

def getMessage():
message= "Hello World"
print(message)
  
getMessage()

# Output
  File "c:ProjectsTryoutslistindexerror.py", line 2
    message= "Hello World"
    ^
IndentationError: expected an indented block

Correct way of indentation while creating a function.

# Proper indentation inside a function

def getMessage():
    message= "Hello World"
    print(message)
  
getMessage()

# Output
Hello World

Example 2 – Indentation inside for, while loops and if statement

Lines inside a for, if, and while statements should be indented more than the line, it begins the statement so that Python will know when you are inside the loop and when you exit the loop.

Suppose you look at the below example inside the if statement; the lines are not indented properly. The print statement is at the same level as the if statement, and hence the IndentationError.

# Bad indentation inside if statement
def getMessage():
    foo = 7
    if foo > 5:
    print ("Hello world")
  
getMessage()

# Output
  File "c:ProjectsTryoutslistindexerror.py", line 4
    print ("Hello world")
    ^
IndentationError: expected an indented block

To fix the issues inside the loops and statements, make sure you add four whitespaces and then write the lines of code. Also do not mix the white space and tabs these will always lead to an error.

# Proper indentation inside if statement
def getMessage():
    foo = 7
    if foo > 5:
        print ("Hello world")
  
getMessage()

# Output
Hello world

Conclusion

The best way to avoid these issues is to always use a consistent number of spaces when you indent a subblock and ideally use a good IDE that solves the problem for you.

Ezoic

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

Программирование, Python, Учебный процесс в IT, Блог компании SkillFactory


Рекомендация: подборка платных и бесплатных курсов PR-менеджеров — https://katalog-kursov.ru/

image

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

1) Пропуск “:” после оператора if, elif, else, for, while, class или def. (Сообщение об ошибке: “SyntaxError: invalid syntax”)

Пример кода с ошибкой:

if spam == 42

    print('Hello!')

2) Использование = вместо ==. (Сообщение об ошибке: “SyntaxError: invalid syntax”)

= является оператором присваивания, а == является оператором сравнения «равно». Пример кода с ошибкой:

if spam = 42:

    print('Hello!')

3) Использование неправильного количества отступов. (Сообщение об ошибке: «IndentationError: unexpected indent» и «IndentationError: unindent does not match any outer indentation level» и «IndentationError: expected an indented block»)

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

print('Hello!')

    print('Howdy!')

… еще:

if spam == 42:

    print('Hello!')

  print('Howdy!')

… еще:

if spam == 42:

print('Hello!')

4) Забыть вызвать len() в операторе цикла for. (Сообщение об ошибке: “TypeError: 'list' object cannot be interpreted as an integer”)

Обычно вы хотите перебирать индексы элементов в списке или строке, что требует вызова функции range(). Просто не забудьте передать возвращаемое значение len(someList) вместо передачи только someList.

Пример кода с ошикой:

spam = ['cat', 'dog', 'mouse']

for i in range(spam):

    print(spam[i])

(UPD: как некоторые указали, вам может понадобиться только for i in spam: вместо приведенного выше кода. Но вышесказанное относится к очень законному случаю, когда вам нужен индекс в теле цикла, а не только само значение.)

5) Попытка изменить строковое значение. (Сообщение об ошибке: “TypeError: 'str' object does not support item assignment”)

Строки являются неизменным типом данных. Пример кода с ошибкой:

spam = 'I have a pet cat.'

spam[13] = 'r'

print(spam)

Пример правильного варианта:

spam = 'I have a pet cat.'

spam = spam[:13] + 'r' + spam[14:]

print(spam)

6) Попытка объединить не строковое значение в строковое значение. (Сообщение об ошибке: “TypeError: Can't convert 'int' object to str implicitly”)

Пример кода с ошибкой:

numEggs = 12
print('I have ' + numEggs + ' eggs.')
Правильный вариант:
numEggs = 12
print('I have ' + str(numEggs) + ' eggs.')

… или:

numEggs = 12
print('I have %s eggs.' % (numEggs))

7) Пропуск кавычки, в начале или конце строкового значения. (Сообщение об ошибке: “SyntaxError: EOL while scanning string literal”)

Пример кода с ошикой:

print(Hello!')

… еще:

print('Hello!)
...еще:
myName = 'Al'
print('My name is ' + myName + . How are you?')

8) Опечатка в переменной или имени функции. (Сообщение об ошибке: “NameError: name 'fooba' is not defined”)

Пример кода с ошибкой:

foobar = 'Al'
print('My name is ' + fooba)
...еще:
spam = ruond(4.2)
...еще:
spam = Round(4.2)

9) Опечатка в названии метода. (Сообщение об ошибке: “AttributeError: 'str' object has no attribute 'lowerr'”)

Пример кода с ошибкой:

spam = 'THIS IS IN LOWERCASE.'
spam = spam.lowerr()

10) Выход за пределы массива. (Сообщение об ошибке: “IndexError: list index out of range”)

Пример кода с ошибкой:

spam = ['cat', 'dog', 'mouse']
print(spam[6])

11) Использование несуществующего ключа словаря. (Сообщение об ошибке: “KeyError: 'spam'”)

Пример кода с ошибкой:

spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam['zebra'])

12) Попытка использовать ключевые слова Python в качестве переменной (Сообщение об ошибке: “SyntaxError: invalid syntax”)

Ключевые слова Python (также называются зарезервированные слова) не могут быть использованы для названия переменных. Ошибка будет со следующим кодом:

class = 'algebra'

Ключевые слова Python 3: and, as, assert, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield

13) Использование расширенного оператора присваивания для новой переменной. (Сообщение об ошибке: “NameError: name 'foobar' is not defined”)

Не думайте, что переменные начинаются со значения, такого как 0 или пустая строка. Выражение с расширенным оператором как spam += 1 эквивалентно spam = spam + 1. Это означает, что для начала в spam должно быть какое-то значение.

Пример кода с ошибкой:

spam = 0
spam += 42
eggs += 42

14) Использование локальных переменных (с таким же именем как и у глобальной переменной) в функции до назначения локальной переменной. (Сообщение об ошибке: “UnboundLocalError: local variable 'foobar' referenced before assignment”)

Использовать локальную переменную в функции, имя которой совпадает с именем глобальной переменной, довольно сложно. Правило таково: если переменной в функции когда-либо назначается что-то, она всегда является локальной переменной, когда используется внутри этой функции. В противном случае, это глобальная переменная внутри этой функции.
Это означает, что вы не можете использовать ее как глобальную переменную в функции до ее назначения.

Пример кода с ошибкой:

someVar = 42
def myFunction():
    print(someVar)
    someVar = 100
myFunction()

15) Попытка использовать range() для создания списка целых чисел. (Сообщение об ошибке: “TypeError: 'range' object does not support item assignment”)

Иногда вам нужен список целочисленных значений по порядку, поэтому range() кажется хорошим способом создать этот список. Однако вы должны помнить, что range() возвращает «объект диапазона», а не фактическое значение списка.

Пример кода с ошибкой:

spam = range(10)
spam[4] = -1
То что вы хотите сделать, выглядит так:
spam = list(range(10))
spam[4] = -1

(UPD: Это работает в Python 2, потому что Python 2’s range() возвращает список значений. Но, попробовав сделать это в Python 3, вы увидите ошибку.)

16) Нет оператора ++ инкремента или -- декремента. (Сообщение об ошибке: “SyntaxError: invalid syntax”)

Если вы пришли из другого языка программирования, такого как C++, Java или PHP, вы можете попытаться увеличить или уменьшить переменную с помощью ++ или --. В Python таких операторов нет.

Пример кода с ошибкой:

spam = 0
spam++
То что вы хотите сделать, выглядит так:
spam = 0
spam += 1

17) UPD: как указывает Luchano в комментариях, также часто забывают добавить self в качестве первого параметра для метода. (Сообщение об ошибке: «TypeError: TypeError: myMethod() takes no arguments (1 given)»)

Пример кода с ошибкой:

class Foo():
    def myMethod():
        print('Hello!')
a = Foo()
a.myMethod()

Краткое объяснение различных сообщений об ошибках приведено в Приложении D книги «Invent with Python».


image
Узнайте подробности, как получить востребованную профессию с нуля или Level Up по навыкам и зарплате, пройдя онлайн-курсы SkillFactory:

  • Курс «Профессия Data Scientist» (24 месяца)
  • Курс «Профессия Data Analyst» (18 месяцев)
  • Курс «Python для веб-разработки» (9 месяцев)

Читать еще

  • 450 бесплатных курсов от Лиги Плюща
  • Бесплатные курсы по Data Science от Harvard University
  • 30 лайфхаков чтобы пройти онлайн-курс до конца
  • Самый успешный и самый скандальный Data Science проект: Cambridge Analytica

Base class of IndentationError is SyntaxError. This exception occurred in Python because of incorrect Indentation because Python don’t use curly brackets for segregate blocks for loop, if-else, functions etc. it’s identify the blocks based on indentation only. Sometime if with in same block there is difference in indentations then it can throw TabError.

Note: Syntax error should not be handle through exception handling it should be fixed in your code.

You can check complete list of built-in exception hierarchy by following link. Python: Built-in Exceptions Hierarchy

Example

Here is simple example of reading the csv file by Python csv module. It’s throwing indentation error because of not proper indentation in second statement.

import csv
   with open(r'C:Userssaurabh.gupta14DesktopPython Exampleinput.csv','r') as csvfile:
    reader=csv.reader(csvfile)
    for record in reader:
        print(record)

Output

File “C:/Users/saurabh.gupta14/Desktop/Python Example/ReadingCSV.py”, line 2
with open(‘C:Userssaurabh.gupta14DesktopPython Example’,’r’) as csvfile:
^
IndentationError: unexpected indent

Solution

In the above example the second line is start from after taking tab which is not required. It should start without taking any space or tab. To fixed this issue i have remove the space and run it again.

import csv
with open(r'C:Userssaurabh.gupta14DesktopPython Exampleinput.csv','r') as csvfile:
    reader=csv.reader(csvfile)
    for record in reader:
        print(record) 

The above modified code with not throw the IndentationError.

Learn Python exception handling in more detain in topic Python: Exception Handling

Let me know your thought on it.

Happy Learning !!!

“Learn From Others Experience»

If you are new to coding or an experienced coder, you might have come across indentation error in python. It looks silly but it can pause the entire process and take good amount of time to fix it. I can help you saving some of your precious time. So, lets dive little deeper into it and understand what is indentation and how to fix it

Python is a procedural language. An indentation in Python is used to segregate a singular code into identifiable groups of functionally similar statements. The indentation error can occur when the spaces or tabs are not placed properly. There will not be an issue if the interpreter does not find any issues with the spaces or tabs. If there is an error due to indentation, it will come in between the execution and can be a show stopper.

Python follows the PEP8 whitespace ethics while arranging its code and therefore it is suggested that there should be 4 whitespaces between every iteration and any alternative that doesn’t have this will return an error.

Below are some of the common causes of an indentation error in Python:

  • While coding you are using both the tab as well as space. While in theory both of them serve the same purpose, if used alternatively in a code, the interpreter gets confused between which alteration to use and thus returns an error.

  • While programming you have placed an indentation in the wrong place. Since python follows strict guidelines when it comes to arranging the code, if you placed any indentation in the wrong place, the indentation error is mostly inevitable.

  • Sometimes in the midst of finishing a long program, we tend to miss out on indenting the compound statements such as for, while and if and this in most cases will lead to an indentation error.

  • Last but not least, if you forget to use user defined classes, then an indentation error will most likely pop up.

Errors due to indentation in Python:

Python determines when code blocks begin and stop by looking at the space at the beginning of the line. You may encounter the following Indentation errors:
1. Unexpected indent — This line of code has more spaces at the beginning than the one before it, but the one before it does not begin a sub block. In a block, all lines of code must begin with the same string of whitespace.
2. Unindent does not correspond to any of the outer indentation levels — This line of code contains less spaces at the beginning than the previous one, but it also does not match any other block.
3. An indented block was expected — This line of code begins with the same number of spaces as the previous one, yet the previous line was supposed to begin a block (e.g., if/while/for statement, function definition).

Few tips to solve an indentation error in Python:

1. While there is no quick fix to this problem, one thing that you need to keep in mind while trying to find a solution for the indentation error is the fact that you have to go through each line individually and find out which one contains the error.

In Python, all the lines of code are arranged according to blocks, so it becomes easier for you to spot an error. For example, if you have used the if statement in any line, the next line must definitely have an indentation.

Take a look at the example below.

If you need guidance on how the correct form of indentation will look like, take a look at the example below.

2. Go to your code editor settings and enable the option that seeks to display tabs and whitespaces. With this feature enabled, you will see single small dots, where each dot represents a tab/white space. If you notice a drop is missing where it shouldn’t be, then that line probably has an indentation error.

For Pycharm, please go to file — settings — editor — code style — python

3. Use the Python interpreter built-in Indent Guide. It takes you through each line and shows you exactly where your error lies, it is the surest way to find and fix all errors.

Conclusion:

Getting errors are inevitable part of programming, so is debugging. One cannot ignore indentation error while working with python but above tips show that it can be easily resolved. Hope this information makes your life little easy and programming journey more exciting.

References:

https://www.edureka.co/blog/indentation-error-in-python/

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Syntaxerror invalid syntax python ошибка
  • Syntax error unexpected php ошибка