Python indentationerror: unindent does not match any outer indentation level Solution
Indenting your code can be a messy business if you try to use both spaces and tabs. In Python, using both methods of indentation results in an error. This error is “indentationerror: unindent does not match any outer indentation level”.
- Career Karma matches you with top tech bootcamps Get exclusive scholarships and prep courses
- Career Karma matches you with top tech bootcamps Get exclusive scholarships and prep courses
In this guide, we talk about what this error means and when it is raised. We walk through an example of this error in action to help you learn how to fix it.
indentationerror: unindent does not match any outer indentation level
Python code can be indented with tabs or spaces. It’s up to you.
Python only has an objection when you use both spaces and tabs to indent your code. Python requires you use only one method of indentation. This is because the language is statically typed. Statically typed programming languages are sticklers when it comes to syntax.
Indentation errors are a difficult one to understand because it involves the invisible: mixing spaces and tabs. Depending on the code editor you are using, you may not even be able to see whether spaces or tabs have been used until you delete your indents from your code.
IndentationErrors are common when you copy code snippets from the internet. Every developer has their own preference when it comes to indentation and you’ll often find code snippets do not adhere to your own preferences. Some snippets will indent with spaces.
If a code snippet you copy into your program uses a different type of indentation, you may see an IndentationError in your code. This is because you mix tabs and spaces.
An Example Scenario
Write a program that finds the factors of a number.
81% of participants stated they felt more confident about their tech job prospects after attending a bootcamp. Get matched to a bootcamp today.
Find Your Bootcamp Match
The average bootcamp grad spent less than six months in career transition, from starting a bootcamp to finding their first job.
Start your career switch today
Start by defining a function to calculate the factors of a number:
This function uses a for loop to iterate through every number in the range of 1 and the number we have specified plus 1.
In each iteration, our program checks if there is a remainder after dividing “number” by “i”. We do this using the modulo operator. If there is not a remainder, “i” is a factor of “number”.
If a number is a factor of “number”, a message is printed to the console.
We to call our function:
This code calculates all the factors of 32. Run our code and see what happens:
IndentationError: undentent не соответствует любому внешнему уровню отступа
Резюме: Ошибка indentationError: undentent не соответствует любому наружным уровню отступа возникновения, если вы используете непоследовательную отступ вкладки или пробела для блоков кода с отступом, таких как блок IF и цикла для цикла. Например, Python выбросит ошибку вдавливания, если вы используете контуру на петлю с четырьмя удалями пробеловных спецификаций для первой строки, а одна вкладка символов вторые … unthencationError: Undentent не соответствует любому уровню внешнего внятия.
IndentationError: undentent не соответствует любому внешнему уровню отступа
Вы, должно быть, надо столкнулись с этой глупой ошибкой в какой-то момент времени, когда кодируют. Разве это не очень расстраивает, чтобы получить ошибку, даже если ваш код логически правильный!
Но после того, как вы прочитаете эту статью, вы, вероятно, никогда не встретите эту ошибку снова. Даже если вы сделаете, вы сможете исправить его во вспышке! Так что без дальнейшей задержки давайте погрузимся в нашу дискуссию на undationeRor в Python.
Отступ в Python
Отступ относится к пробелам в начале строки кода.
В Python отступа является неотъемлемой функцией, которая представляет собой блок кода и определяет выполнение вашего кода. Когда вы пропустите правильные отступы, Python бросит IndentationError Отказ
Каждая строка кода в блоке должна иметь равное количество пробелов перед ними. Это означает, что если для Блок петли содержит две строки кода, затем каждая строка должна иметь четыре пробела (в идеале) перед ними. Если одна строка кода имеет три пробела, а другая имеет четыре, вы снова получите IndentationError Отказ
Пример 1.
Учитывая список, содержащий марки. На основании данных условий следующая программа направлена на разрыв каждого номера в списке в определенную оценку.
В приведенном выше примере ошибка произошла в еще Заявление, потому что он не следует правильному отступе.
📖 Как исправить “unthationerror: undentent не соответствует любому внешнему уровню отступа”
➥ Чтобы исправить JentationError: undentent не совпадает с любым внешним уровнем отступа Используйте одинаковое количество пробелов для каждой строки кода в данном блоке.
✍️ Примечание :
Давайте посмотрим на другой пример, чтобы убедиться, что у вас есть четкое представление о причине возникновения такой ошибки.
Пример 2.
Следующая программа используется для поиска факториала номера, введенного пользователем.
Вышеуказанная ошибка произошла из-за линии 6, которая указывает на то, что Отчет о возврате имеет неправильное отступление. Это произошло потому, что мы смешали вкладки и промежутки в нашем коде для отступа к блоку кода в функции.
Чтобы избежать этой ошибки, вы можете использовать вкладку или 4 пробела (рекомендуется) перед каждой строкой внутри функции. Обратите внимание, что блок внутри петли должен иметь 8 белых пробелов.
🔰 Избегайте или исправьте entionationeRror в редакторах кода
Из приведенных выше примеров очевидно, что основная причина позади IndentationError В Python это Неправильное использование пробелов и вкладок В вашей программе. В большинстве редакторов кода вы можете исправить количество пробеловных символов/вкладок WhiteSpace by Установка уровней отступа.
Давайте посмотрим на настройки в различных редакторах кода, которые позволяют нам Автофункф Наш код или исправить ранее существующие ошибки:
📝 возвышенный текст
📝 Блокнот ++
Следуйте приведенным ниже настройкам, чтобы просмотреть вкладки или Пробелы в Notepad ++.
🔰 Использование IDE
Преимущество использования IDE, как Пычарм Это то, что вам не нужно беспокоиться о углублениях в вашем коде вручную, поскольку это позаботится о самом IDE как шоу в презентации, приведенной ниже.
Вывод
Я надеюсь, что вам понравилось читать эту статью и узнал, как исправить Ошибки вдавливания в Python Отказ Пожалуйста, Подписаться и Оставайтесь настроиться Для более интересных статей в будущем!
📕 Подробнее: Python indentationError: неожиданный отступ (как исправить эту глупую ошибку)
Куда пойти отсюда?
Достаточно теории, давайте познакомимся!
Чтобы стать успешным в кодировке, вам нужно выйти туда и решать реальные проблемы для реальных людей. Вот как вы можете легко стать шестифункциональным тренером. И вот как вы польские навыки, которые вам действительно нужны на практике. В конце концов, что такое использование теории обучения, что никто никогда не нуждается?
Практические проекты – это то, как вы обостряете вашу пилу в кодировке!
Вы хотите стать мастером кода, сосредоточившись на практических кодовых проектах, которые фактически зарабатывают вам деньги и решают проблемы для людей?
Затем станьте питоном независимым разработчиком! Это лучший способ приближения к задаче улучшения ваших навыков Python – даже если вы являетесь полным новичком.
Присоединяйтесь к моему бесплатным вебинаре «Как создать свой навык высокого дохода Python» и посмотреть, как я вырос на моем кодированном бизнесе в Интернете и как вы можете, слишком от комфорта вашего собственного дома.
Присоединяйтесь к свободному вебинару сейчас!
Я профессиональный Python Blogger и Content Creator. Я опубликовал многочисленные статьи и создал курсы в течение определенного периода времени. В настоящее время я работаю полный рабочий день, и у меня есть опыт в областях, таких как Python, AWS, DevOps и Networking.
IndentationError: unindent does not match any outer indentation level
When I compile the Python code below, I get
IndentationError: unindent does not match any outer indentation level
/.editorconfig file that was overriding the pycharm configuration.
35 Answers 35
Other posters are probably correct. there might be spaces mixed in with your tabs. Try doing a search & replace to replace all tabs with a few spaces.
For Sublime Text users:
Uncheck the Indent Using Spaces option as well in the same sub-menu above. This will immediately resolve this issue.
To easily check for problems with tabs/spaces you can actually do this:
or you can just set up your editor correctly of course 🙂
Are you sure you are not mixing tabs and spaces in your indentation white space? (That will cause that error.)
Note, it is recommended that you don’t use tabs in Python code. See the style guide. You should configure Notepad++ to insert spaces for tabs.
Whenever I’ve encountered this error, it’s because I’ve somehow mixed up tabs and spaces in my editor.
If you are using Vim, hit escape and then type
This auto indents everything and will clear up any spaces you have thrown in.
If you use Python’s IDLE editor you can do as it suggests in one of similar error messages:
1) select all, e.g. Ctrl + A
3) Double check your indenting is still correct, save and rerun your program.
I’m using Python 2.5.4
The line: result = result * i should be indented (it is the body of the for-loop).
Then check again your file indentation:
For Spyder users goto Source > Fix Indentation to fix the issue immediately
If you use notepad++, do a «replace» with extended search mode to find \t and replace with four spaces.
Looks to be an indentation problem. You don’t have to match curly brackets in Python but you do have to match indentation levels.
The best way to prevent space/tab problems is to display invisible characters within your text editor. This will give you a quick way to prevent and/or resolve indentation-related errors.
Also, injecting copy-pasted code is a common source for this type of problem.
Using Visual studio code
If you are using vs code than, it will convert all mix Indentation to either space or tabs using this simple steps below.
press Ctrl + Shift + p
type indent using spaces
Just a addition. I had a similar problem with the both indentations in Notepad++.
Outer Indentation Level
I was using Jupyter notebook and tried almost all of the above solutions (adapting to my scenario) to no use. I then went line by line, deleted all spaces for each line and replaced with tab. That solved the issue.
For what its worth, my docstring was indented too much and this also throws the same error
IndentationError: unindent does not match any outer indentation level
I’m using Sublime text in Ubuntu OS. To fix this issue go to
It could be because the function above it is not indented the same way. i.e.
I am using Sublime Text 3 with a Flask project. I fixed the error using View > Indentation > Tab Width: 4 after unselected Indent Using Spaces
This is because there is a mix-up of both tabs and spaces. You can either remove all the spaces and replace them with tabs.
Or, Try writing this:
at the beginning of the code. This line resolves any differences between tabs and spaces.
I had the same issue yesterday, it was indentation error, was using sublime text editor. took my hours trying to fix it and at the end I ended up copying the code into VI text editor and it just worked fine. ps python is too whitespace sensitive, make sure not to mix space and tab.
I had a function defined, but it did not had any content apart from its function comments.
(note that the line the ^ mark points to is empty)
1: Just comment out the function
2: Add function comment
3: Add line that does nothing
Firstly, just to remind you there is a logical error you better keep result=1 or else your output will be result=0 even after the loop runs.
Secondly you can write it like this:
Leaving a line will tell the python shell that the FOR statements have ended. If you have experience using the python shell then you can understand why we have to leave a line.
I got this error even though I didn’t have any tabs in my code, and the reason was there was a superfluous closing parenthesis somewhere in my code. I should have figured this out earlier because it was messing up spaces before and after some equal signs. If you find anything off even after running Reformat code in your IDE (or manually running autopep8), make sure all your parentheses match, starting backwards from the weird spaces before/after the first equals sign.
Unindent does not match any outer indentation level
On line 51/52, I get the error:
Unindent does not match any outer indentation level.
I understand this has something to do with tabs and spaces.
Note I did not write this code, I found it online and plan to modify it.
Full code (also at http://pastebin.com/n7ML6Rpz)
2 Answers 2
Python code is sensitive to the indent level you use. Your code reads:
Inside the if block, the statements must all line up. Notice how client_socket.close() and the following print statement have different indent levels. You need to change this so that they both have the same indent, like this:
The code presently reads:
The first statement in the body of the if is indented 6 spaces, while the last two statements are only indented by 1 space. The indentation level ought to be same and consistent throughout the program, something like this:
The indentation in the code doesn’t seem very standard (or consistent). For instance the body of the while loop in 41/42 is indented more than other bodies of similar statements, e.g., lines 31-33, that’s trouble in a language like Python where whitespace matters.
Not the answer you’re looking for? Browse other questions tagged python indentation or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.11.12.40742
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
SyntaxError: unindent does not match any outer indentation level
I keep having this problem. I am new into Python but I want to learn it seriously and I am struggling with this error. I made research about indentation and tried to review my few lines of code but with no succes. I cannot understand why it keeps appearing as I tried not to mix tabs and spaces. Thanks in advance for help! (I am currently running Python 3.6.4)
4 Answers 4
add or print some thing in else block. It will resolve your issue.
Try the below code without the else block and see if it still gives you the same error.
Ok i am also using a Python SoloLearn app and tried to write the same code in the Code Playground and it works just fine. I also did use my fathers laptop and looks ok there too. (He is using 3.3. or similar). So I can only say that maybe its some kind of weird bug occuring on my laptop or on 3.6.4. Anyway thank you all for answers and fast reply. I just wanted to be sure its not my bad and now I’m pretty sure its not :))
The editor use tab, so after the end of a block and press ‘Enter’, it add automaticly an indentation. Then just press ‘Backspace’ (or ‘Tab’) to align to the correct block.
You notice that the first ‘else:’ is align to the start of line.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.11.12.40742
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.




















