Indentationerror unexpected indent что за ошибка

1 ответ

Если бы вы перевели текст ошибки, вы бы поняли, что у вас проблема с отступами.
Обратите внимание на отступ перед import.

Напоминаю, что в python блоки кода разграничиваются отступами.

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

На основе этого ответа.

В данном случае отступ вообще следует удалить.

ответ дан 26 фев 2016 в 21:13

VenZell's user avatar

VenZellVenZell

19.9k5 золотых знаков44 серебряных знака61 бронзовый знак

1

  • Окей , у меня такая же проблема но в коде .( Я учусь и решил написать простой калькулятор) Но удаляю абсолютно все отступы которые присутствуют в коде и все равно также ошибка .

    26 фев 2019 в 13:38

Вопросик, я только начал изучать питон, учусь по книжке, там говорят про отступы, но почему выдает ошибку IndentationError: unexpected indent? там не перемешаны пробелы и табы, я пробовал и 4 пробела везде проставить и табы, ошибка одна( код вообще рандомный, просто для проверки сделал)

df = (200, 300)
	print('обычный форма:')
	print(df)

df = (300, 400)
	print('\nмодернизация:')
	print(df)


  • Вопрос задан

  • 10452 просмотра

Так и пишет, неожиданный отступ.

Если код так и выглядит

df = (200, 300)
  print('обычный форма:')
  print(df)

df = (300, 400)
  print('\nмодернизация:')
  print(df)

То ошибка вполне логична, перед print() зачем-то стоят отступы, которых быть не должно

Пригласить эксперта


  • Показать ещё
    Загружается…

10 дек. 2023, в 02:44

40000 руб./за проект

09 дек. 2023, в 23:51

1500 руб./за проект

09 дек. 2023, в 22:48

1000 руб./в час

Минуточку внимания

Fluent Programming|

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:\Projects\Tryouts\listindexerror.py", line 2
    message= "Hello World"
    ^
IndentationError: expected an indented block

# Proper indentation inside a function

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

getMessage()

# Output
Hello World

Enter fullscreen mode

Exit fullscreen mode

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:\Projects\Tryouts\listindexerror.py", line 4
    print ("Hello world")
    ^
IndentationError: expected an indented block

Enter fullscreen mode

Exit fullscreen mode

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

Enter fullscreen mode

Exit fullscreen mode

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.

The post IndentationError: unexpected indent appeared first on Fluent Programming.

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

Ошибка «unexpected indent» в Python

unexpected indent

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

IndentationError: unexpected indent

Исключение IndentationError является подклассом SyntaxError. Оно срабатывает, когда Python парсирует отступ, которого там быть не должно.

Это чистая синтаксическая ошибка, которую обычно допускают новички. Например, распространенная ошибка при написании оператора if-else в Python:

a = 1;

if a:
print(«The statement is true»)
print(a)
else:
print(«The statement is false»)
print(a)

И в результате вы получите вот такое сообщение:

File «code.py», line 5
print(a)
IndentationError: unexpected indent

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

Что такое отступы?

В то время как во многих других языках программирования, таких как Java, HTML или C++, для обозначения блоков кода используются фигурные скобки {}, в Python используется отступ. Отступы – это пробельные символы, которыми начинается строка кода. Его необходимо использовать для начала блока кода (например, тела оператора if или функции).

Как программист, вы вольны выбирать способ использования табуляции или пробелов для создания отступа. Но он должен быть представлен для указания блока кода. Можно записать весь блок в одну строку, используя точку с запятой. Однако всегда лучше вместо этого сделать отступ. Сравните эти два фрагмента, которые оба являются корректными и выполняют одну и ту же задачу.

Сниппет 1

a = 28
b = 22

if a > b:
print(«a is greater than b») # a is greater than b

Сниппет 2

a = 28
b = 22

if a > b: print(«a is greater than b») # a is greater than b

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

Правила отступов

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

Однако для этой цели можно также использовать табуляцию или восемь пробелов. Это зависит как от личных предпочтений, так и от требований проекта. Только следите за тем, чтобы не вставлять лишние отступы во избежание ошибки «unexpected indent».

Вы можете оформить каждый блок кода по-своему (хотя это плохая практика программирования). Python все равно выполнит их нормально. Но если в одном блоке кода будет несколько уровней отступов, он покажет исключение IndentationError.

Заключение

Отступы  – это отличительная и важная особенность Python. Не понимая ее, вы можете столкнуться с такими распространенными проблемами, как ошибка «unexpected indent». Однако это легко исправить, так как можно переформатировать блок кода, чтобы убрать сообщение об ошибке.

Ad

At Career Karma, our mission is to empower users to make confident decisions by providing a trustworthy and free directory of bootcamps and career resources. We believe in transparency and want to ensure that our users are aware of how we generate revenue to support our platform.

Career Karma recieves compensation from our bootcamp partners who are thoroughly vetted before being featured on our website. This commission is reinvested into growing the community to provide coaching at zero cost to their members.

It is important to note that our partnership agreements have no influence on our reviews, recommendations, or the rankings of the programs and services we feature. We remain committed to delivering objective and unbiased information to our users.

In our bootcamp directory, reviews are purely user-generated, based on the experiences and feedback shared by individuals who have attended the bootcamps. We believe that user-generated reviews offer valuable insights and diverse perspectives, helping our users make informed decisions about their educational and career journeys.

Find the right bootcamp for you

ck-logo

X

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.

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

Понравилась статья? Поделить с друзьями:
  • Ims service что это ошибка
  • Indentationerror expected an indented block что за ошибка
  • Immergas e10 ошибка как сделать сброс
  • Immergas nike star коды ошибок
  • Indentationerror expected an indented block питон ошибка