Python ошибка отступа неожиданный отступ

Python uses spacing at the start of the line to determine when code blocks start and end. Errors you can get are:

Unexpected indent. This line of code has more spaces at the start than the one before, but the one before is not the start of a subblock (e.g., the if, while, and for statements). All lines of code in a block must start with exactly the same string of whitespace. For instance:

>>> def a():
...   print "foo"
...     print "bar"
IndentationError: unexpected indent

This one is especially common when running Python interactively: make sure you don’t put any extra spaces before your commands. (Very annoying when copy-and-pasting example code!)

>>>   print "hello"
IndentationError: unexpected indent

Unindent does not match any outer indentation level. This line of code has fewer spaces at the start than the one before, but equally it does not match any other block it could be part of. Python cannot decide where it goes. For instance, in the following, is the final print supposed to be part of the if clause, or not?

>>> if user == "Joey":
...     print "Super secret powers enabled!"
...   print "Revealing super secrets"
IndendationError: unindent does not match any outer indentation level

Expected an indented block. This line of code has the same number of spaces at the start as the one before, but the last line was expected to start a block (e.g., if, while, for statements, or a function definition).

>>> def foo():
... print "Bar"
IndentationError: expected an indented block

If you want a function that doesn’t do anything, use the «no-op» command pass:

>>> def foo():
...     pass

Mixing tabs and spaces is allowed (at least on my version of Python), but Python assumes tabs are 8 characters long, which may not match your editor. Don’t mix tabs and spaces. Most editors allow automatic replacement of one with the other. If you’re in a team, or working on an open-source project, see which they prefer.

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. This will also make your code more readable.

Автор оригинала: Chris.

Если вы похожи на меня, вы сначала попробуйте все в своем коде и исправить ошибки, как они приходят. Одна частая ошибка в Python – IndentationError: неожиданный отступ Отказ Итак, что означает это сообщение об ошибке?

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

Давайте посмотрим на пример, где возникает эта ошибка:

for i in range(10):
  print(i)
   print('--')

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

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

for i in range(10):
    print(i)
    print('--')

Общая рекомендация состоит в том, чтобы использовать четыре единственных пробелных персонажей '' для каждого Отступ уровень. Если у вас вложенные уровни вдавливания, это означает, что второй уровень вдавливания имеет одновение пробелы:

for i in range(10):
    for j in range(10):
        print(i, j)

Смесительные вкладки и пробелы частоты часто вызывают ошибку

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

На первый взгляд углубление выглядит одинаково. Однако, если вы пройдете пробелы перед Печать (I) , вы видите, что он состоит только из одного табличного характера, в то время как пробелы перед Распечатать (j) Заявление состоит из ряда пустых мест '' Отказ

Попробуйте сами: Прежде чем я скажу вам, что делать с этим, попробуйте исправить код себя в нашей интерактивной оболочке Python:

Упражнение : Исправьте код в оболочке интерактивного кода, чтобы избавиться от сообщения об ошибке.

Вы хотите развивать навыки Хорошо округлый Python Professional То же оплачивается в процессе? Станьте питоном фрилансером и закажите свою книгу Оставляя крысиную гонку с Python На Amazon ( Kindle/Print )!

Как исправить ошибку отступа на все времена?

Источник ошибки часто является неправильным использованием вкладок и пробеловных символов. Во многих редакторах кода вы можете установить символ вкладки на фиксированное количество символов пробела. Таким образом, вы, по сути никогда не используете сам табличный символ. Например, если у вас есть Sublime Text Editor, следующее быстрое руководство гарантирует, что вы никогда не будете работать в этой ошибке:

  • Установить Возвышенный текст Использовать вкладки для отступа: Вид -> Отступ -> Преобразовать вдавшиеся вкладки
  • Снимите флажок Опция Отступ с использованием пробелов в том же подменю выше.

Куда пойти отсюда?

Достаточно теории, давайте познакомимся!

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

Практические проекты – это то, как вы обостряете вашу пилу в кодировке!

Вы хотите стать мастером кода, сосредоточившись на практических кодовых проектах, которые фактически зарабатывают вам деньги и решают проблемы для людей?

Затем станьте питоном независимым разработчиком! Это лучший способ приближения к задаче улучшения ваших навыков Python – даже если вы являетесь полным новичком.

Присоединяйтесь к моему бесплатным вебинаре «Как создать свой навык высокого дохода Python» и посмотреть, как я вырос на моем кодированном бизнесе в Интернете и как вы можете, слишком от комфорта вашего собственного дома.

Присоединяйтесь к свободному вебинару сейчас!

Работая в качестве исследователя в распределенных системах, доктор Кристиан Майер нашел свою любовь к учению студентов компьютерных наук.

Чтобы помочь студентам достичь более высоких уровней успеха Python, он основал сайт программирования образования Finxter.com Отказ Он автор популярной книги программирования Python One-listers (Nostarch 2020), Coauthor of Кофе-брейк Python Серия самооставленных книг, энтузиаста компьютерных наук, Фрилансера и владелец одного из лучших 10 крупнейших Питон блоги по всему миру.

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

Here is my code … I am getting indentation error but i don’t know why it occurs.

->

# loop
while d <= end_date:
    # print d.strftime("%Y%m%d")
    fecha = d.strftime("%Y%m%d")
    # set url
    url = 'http://www.wpemergencia.omie.es//datosPub/marginalpdbc/marginalpdbc_' + fecha + '.1'
    # Descargamos fichero
    response = urllib2.urlopen(url)
    # Abrimos fichero
    output = open(fname,'wb')
    # Escribimos fichero
    output.write(response.read())
    # Cerramos y guardamos fichero
    output.close()
    # fecha++
    d += delta

Rory Daulton's user avatar

Rory Daulton

22k6 gold badges42 silver badges50 bronze badges

asked Dec 26, 2011 at 10:03

miguelfg's user avatar

3

Run your program with

python -t script.py

This will warn you if you have mixed tabs and spaces.

On *nix systems, you can see where the tabs are by running

cat -A script.py

and you can automatically convert tabs to 4 spaces with the command

expand -t 4 script.py > fixed_script.py

PS. Be sure to use a programming editor (e.g. emacs, vim), not a word processor, when programming. You won’t get this problem with a programming editor.

PPS. For emacs users, M-x whitespace-mode will show the same info as cat -A from within an emacs buffer!

answered Dec 26, 2011 at 10:08

unutbu's user avatar

unutbuunutbu

845k184 gold badges1787 silver badges1678 bronze badges

3

find all tabs and replaced by 4 spaces in notepad ++ .It worked.

answered May 15, 2013 at 21:31

user2287824's user avatar

user2287824user2287824

1012 silver badges4 bronze badges

1

Check if you mixed tabs and spaces, that is a frequent source of indentation errors.

Daniel Fischer's user avatar

answered Dec 26, 2011 at 10:05

ilstam's user avatar

ilstamilstam

1,4734 gold badges18 silver badges32 bronze badges

You can’t mix tab and spaces for identation. Best practice is to convert all tabs to spaces.

How to fix this? Well just delete all the spaces/tabs before each line and convert them uniformly either to tabs OR spaces, but don’t mix. Best solution: enable in your Editor the option to convert automagically any tabs to spaces.

Also be aware that your actual problem may lie in the lines before this block, and python throws the error here, because of a leading invalid indentation which doesn’t match the following identations!

Velociraptors's user avatar

answered Dec 26, 2011 at 10:10

Don Question's user avatar

Don QuestionDon Question

11.2k5 gold badges36 silver badges54 bronze badges

Simply copy your script and put under «»» your entire code «»» …

specify this line in a variable.. like,

a = """ your entire code """
print a.replace('    ','    ') # first 4 spaces tab second four space from space bar

print a.replace('here please press tab button it will insert some space"," here simply press space bar four times")
# here we replacing tab space by four char space as per pep 8 style guide..

now execute this code, in sublime using ctrl+b, now it will print indented code in console. that’s it

answered Feb 11, 2016 at 12:39

Mohideen bin Mohammed's user avatar

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

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

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


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

  • 8365 просмотров

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

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

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

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

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

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


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

21 сент. 2023, в 19:28

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

21 сент. 2023, в 19:06

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

21 сент. 2023, в 19:00

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

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

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:\Projects\Tryouts\listindexerror.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:\Projects\Tryouts\listindexerror.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.

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.

Понравилась статья? Поделить с друзьями:
  • Qt creator настройки android содержат ошибки
  • Python ошибка импорта модуля
  • Python ошибка dataframe object is not callable
  • Qsx15 cummins коды ошибок
  • Python ошибка времени исполнения