What to do with "Unexpected indent" in python?
PythonIndentationPython Problem Overview
How do I rectify the error "unexpected indent" in python?
Python Solutions
Solution 1 - 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. Just say "no" to tabs. Most editors allow them to be automatically replaced by spaces.
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.
Solution 2 - Python
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.
Solution 3 - Python
Run your code with the -tt option to find out if you are using tabs and spaces inconsistently.
Solution 4 - Python
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 4 spaces is the recommended approach for writing Python code.
Solution 5 - Python
By using correct indentation. Python is white space aware, so you need to follow its indentation guidelines for blocks or you'll get indentation errors.
Solution 6 - Python
If 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.
Solution 7 - Python
Run the following command to get it solved:
autopep8 -i <filename>.py
This will update your code and solve all indentation errors :)
Solution 8 - Python
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
Solution 9 - Python
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!
Solution 10 - Python
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.
Solution 11 - Python
If the indentation looks ok then have a look to see if your editor has a "View Whitespace" option. Enabling this should allow to find where spaces and tabs are mixed.
Solution 12 - Python
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.
Solution 13 - Python
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.
Solution 14 - Python
All you need to do is remove spaces or tab spaces from the start of the following code:
from django.contrib import admin
# Register your models here.
from .models import Myapp
admin.site.register(Myapp)
Solution 15 - Python
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.
Solution 16 - Python
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.
Solution 17 - Python
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]]
Solution 18 - Python
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.