How do I rectify the error "unexpected indent" in Python?
-
8A code fragment that produces the error will help us understand your problem better. Please edit your question to include some code.RBerteig– RBerteig2009-06-19 07:58:58 +00:00Commented Jun 19, 2009 at 7:58
-
8This sounds like a whitespace issue to me so a code sample would be useless.James McMahon– James McMahon2009-06-19 11:28:43 +00:00Commented Jun 19, 2009 at 11:28
-
Vague question and no answer choosen.rafael.js– rafael.js2012-10-17 06:16:56 +00:00Commented Oct 17, 2012 at 6:16
-
"How do I rectify the error ..."? By identifying where it occurred and fixing the cause of the error. In this case, by making the indentation of that particular line look like what Python is expecting...twalberg– twalberg2014-06-13 15:53:18 +00:00Commented Jun 13, 2014 at 15:53
-
1@baptx In every language with braces, coders end up adopting formatting rules where they indent if/else blocks anyway, and major bugs have been introduced when the indentation and the braces misalign by mistake. Python prevents this class of bug. In future, I'd recommend "commenting out" your if by prefacing the condition with "true or (...)" if you don't want to reindent the nested code. That has the exact same effect as a comment.alicederyn– alicederyn2021-12-15 08:50:58 +00:00Commented Dec 15, 2021 at 8:50
19 Answers
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.
6 Comments
except part of a try clause. The code looks right (in that the unindented line is meant to be outside the try block) but Python reports this as an 'unexpected indent' error. This is fixed by adding the except, perhaps using pass (like here)In Python, the spacing is very important. This gives the structure of your code blocks.
This error happens when you mess up your code structure, for example like this:
def test_function():
if 5 > 3:
print "hello"
You may also have a mix of tabs and spaces in your file.
I suggest you use a Python syntax aware editor, like PyScripter, or NetBeans.
5 Comments
Run your code with the -tt option to find out if you are using tabs and spaces inconsistently.
1 Comment
Turn on visible whitespace in whatever editor you are using and turn on replace tabs with spaces.
While you can use tabs with Python, mixing tabs and space usually leads to the error you are experiencing. Replacing tabs with four spaces is the recommended approach for writing Python code.
5 Comments
"editor.renderWhitespace": "all"vscodeIf you're writing Python using Sublime Text and are getting indentation errors,
Menu View → Indentation → Convert indentation to spaces
The issue I'm describing is caused by the Sublime Text editor. The same issue could be caused by other editors as well. Essentially, the issue has to do with Python wanting to treat indentations in terms of spaces versus various editors coding the indentations in terms of tabs.
3 Comments
One issue which doesn't seem to have been mentioned is that this error can crop up due to a problem with the code that has nothing to do with indentation.
For example, take the following script:
def add_one(x):
try:
return x + 1
add_one(5)
This returns an IndentationError: unexpected unindent when the problem is of course a missing except: statement.
My point: check the code above where the unexpected (un)indent is reported!
1 Comment
Make sure you use the option "Insert spaces instead of tabs" in your editor. Then you can choose you want a tab width of, for example 4. You can find those options in gedit under menu Edit → preferences → Editor.
Bottom line: use spaces, not tabs
Comments
This error can also occur when pasting something into the Python interpreter (terminal/console).
Note that the interpreter interprets an empty line as the end of an expression, so if you paste in something like
def my_function():
x = 3
y = 7
the interpreter will interpret the empty line before y = 7 as the end of the expression, i.e. that you're done defining your function, and the next line - y = 7 will have incorrect indentation because it is a new expression.
1 Comment
It depends in the context. Another scenario which wasn't yet covered is the following. Let's say you have one file with a class with a specific method in it
class Scraper:
def __init__(self):
pass
def scrape_html(self, html: str):
pass
and in the bottom of the file you have something like
if __name__ == "__main__":
# some
# commands
# doing
# stuff
making it the whole file look like this
class Scraper:
def __init__(self):
pass
def scrape_html(self, html: str):
pass
if __name__ == "__main__":
# some
# commands
# doing
# stuff
If in scrape_html() you open up, for example, an if/else statement
class Scraper:
def __init__(self):
pass
def scrape_html(self, html: str):
if condition:
pass
else:
if __name__ == "__main__":
parser = argparse.ArgumentParser()
You'll need to add pass or whatever you want to to that else statement or else you'll get
Expected indented block
Unindent not expected
Expected expression
and in the first row
Unexpected indentation
Adding that pass would fix all of these four problems.
Comments
There is a trick that always worked for me:
If you got an unexpected indent and you see that all the code is perfectly indented, try opening it with another editor and you will see what line of code is not indented.
It happened to me when I used Vim, gedit, or editors like that.
Try to use only one editor for your code.
Comments
Simply copy your script, and put it under """ your entire code """ ...
Specify this line in a variable... like,
a = """ your Python script """
print a.replace("Here please press the tab button. It will insert some space", " here simply press the space bar four times.")
#
# Here we are replacing tab space by four character
# space as per the PEP 8 style guide...
#
# Now execute this code. In the Sublime Text
# editor use Ctrl + B. Now it will print
# indented code in the console. That's it.
2 Comments
Notepad++ was giving the tab space correct, but the indentation problem was finally found in the Sublime Text editor.
Use the Sublime Text editor and go line by line.
Comments
Indentation in Python is important and this is just not for code readability, unlike many other programming languages.
If there is any white space or tab in your code between consecutive commands, Python will give this error as Python is sensitive to this. We are likely to get this error when we do copy and paste of code to any Python.
Make sure to identify and remove these spaces using a text editor like Notepad++ or manually remove the whitespace from the line of code where you are getting an error.
# Step 1: Gives an error
L = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
print(L[2: ])
# Step 2: L = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]print(L[2: ])
# Step 3: No error after space was removed
L = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
print(L[2: ])
# Output: [[7, 8, 9, 10]]
Comments
It depends on the context, but an indentation error is often caused by using tabs instead of spaces.
Here are some steps you can take to correct this:
Copy the tabs or spaces that are causing the error
Do a find and replace in your IDE (usually Ctrl + H).
Paste the copied tabs or spaces into the "Find" search bar, and then replace them all with four spaces (assuming that your IDE uses four spaces as a "good" indentation)
This error also happens a lot if you are copying and pasting code from external sources into your IDE, because the formatting elsewhere may not match your IDE's definition for what counts as a "good" indentation.



