How do I rectify the error "unexpected indent" in python?
This question is related to
python
indentation
Run the following command to get it solved :
autopep8 -i <filename>.py
This will update your code and solve all indentation Errors :)
Hope this will solve
Run your code with the -tt option to find out if you are using tabs and spaces inconsistently
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.
Step1 :Gives error
L = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
print(L[2: ])
Step2: L = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]print(L[2: ])
Step3: 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]]
Thanks!
If you're writing Python using Sublime and getting indentation errors,
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.
All You need to do is remove spaces or tab spaces from the start of following codes
from django.contrib import admin
# Register your models here.
from .models import Myapp
admin.site.register(Myapp)
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. if/while/for statement). 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 statement, 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.
Notepad++ was giving the tab space correct but the indentation problem was finally found in Sublime text editor.
Use Sublime text editor and go line by line
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!
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.
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.
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.
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.
Simply copy your script and put under """ your entire code """ ...
specify this line in a variable.. like,
a = """ your python script """
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 Editor using ctrl+b, now it will print indented code in console. that's it
There is a trick that always worked for me:
If you got and 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 used vim, gedit or editors like that.
Try to use only 1 editor for your code.
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
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 edit-->preferences-->editor.
bottom line: USE SPACES not tabs
By using correct indentation. Python is whitespace aware, so you need to follow its indentation guidlines for blocks or you'll get indentation errors.
Source: Stackoverflow.com