172

How do I rectify the error "unexpected indent" in Python?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 8
    A code fragment that produces the error will help us understand your problem better. Please edit your question to include some code. – RBerteig Jun 19 '09 at 07:58
  • 8
    This sounds like a whitespace issue to me so a code sample would be useless. – James McMahon Jun 19 '09 at 11:28
  • Vague question and no answer choosen. – rafael.js Oct 17 '12 at 06: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 Jun 13 '14 at 15:53
  • I got this error because I wanted to comment an if condition and execute the code without condition. So with Python, it is not possible to comment an if condition without changing the indentation of the code block? This would be an annoying language design. – baptx Aug 21 '20 at 18:42
  • 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. – Alice Purcell Dec 15 '21 at 08:50

19 Answers19

173

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.

Alice Purcell
  • 12,622
  • 6
  • 51
  • 57
  • 9
    good explanation. Besides that, I also spent indent Unexpected error when he mixed spaces with 'tab' and 'space bar' in NotePad ++, replace the 'tab' for 'spaces' and fixed. – José Rosas Sáenz Apr 07 '15 at 21:42
  • 2
    @JoséRosasSáenz Your comment saved me so much trouble – user3726345 Oct 19 '16 at 18:21
  • One additional cause is missing out the `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](https://stackoverflow.com/a/730778/575530)) – dumbledad Mar 22 '19 at 11:00
  • @dumbledad Which version of python do you see that on? When I try on mine (both 2.7.15 and 3.6.8), I get a SyntaxError – Alice Purcell Mar 25 '19 at 16:42
  • I encountered this error when copy/pasting code from a website. The positioning appeared ok but i needed to remove the white-space and re-apply using spaces before QGIS(3.10) would run the code. – benj Nov 28 '19 at 16:41
  • Re *"Python assumes tabs are 8 characters long"*: Perhaps add a source for that? (But ***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today.) – Peter Mortensen May 14 '22 at 14:23
24

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
yanjost
  • 5,223
  • 2
  • 25
  • 28
  • 1
    Yes definitely use python-aware editors! I had a problem where I was editing in notepad++ with default settings and it was getting the whitespace wrong – Dave Archer Jun 19 '09 at 08:13
  • 3
    mixed tabs and spaces raise "SyntaxError: inconsistent use of tabs and spaces in indentation" – SilentGhost Jun 19 '09 at 10:22
  • Just as a heads up, the Python Netbeans plugin currently doesn't convert tabs into spaces from existing code. However, it will do it as you write new code. – James McMahon Jun 19 '09 at 11:27
  • PyCharm can convert it consistently. Also it will highlight the lines at "fault". I use quotes because this is not the 1960s and I can't believe a wonderful language such as Python still has this brain-dead, time-wasting flaw. – Echelon Feb 09 '12 at 23:14
  • I unintentionally switched editors halfway through writing my code and it stuffed up my indents in the newer code. The change wasn't obvious to the eye, but the interpreter wouldn't run my code. This post helped me find the problem. – Lucien Stals Nov 23 '15 at 05:46
22

Run your code with the -tt option to find out if you are using tabs and spaces inconsistently.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Manoj I
  • 1,089
  • 1
  • 13
  • 18
  • 3
    What implementation of a Python interpreter? What version? Can you add a reference to (official) documentation. (But ***without*** "Edit:", "Update:", or similar - the question/answer should appear as if it was written today.) – Peter Mortensen May 14 '22 at 14:08
21

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
James McMahon
  • 48,506
  • 64
  • 207
  • 283
  • 1
    How do you specifically do this? I am using Sublime. – chibole Dec 30 '17 at 10:13
  • @chibole Not sure if this is still relevant, but open your Sublime preferences and change "draw_white_space" to "all", "tab_size" to 4 (should be default) and "translate_tabs_to_spaces" to true – bqback Feb 16 '21 at 13:09
  • 1
    In VSCode you can do this with `"editor.renderWhitespace": "all"` – Paul Razvan Berg Sep 14 '21 at 21:51
  • @PaulRazvanBerg it does not change my code in `vscode`. I do not see whitespaces. My version is 1.71, so your code should work. [Here](https://stackoverflow.com/a/30140625/1705829) is more info. Now it works, I have dark mode and the spaces are hardly visible. – Timo Oct 10 '22 at 15:34
  • It seems that tab and space looks similar with dots when using the whitespace setting from @PaulRazvanBerg for `vscode` – Timo Oct 10 '22 at 15:40
11

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
workmad3
  • 25,101
  • 4
  • 35
  • 56
9

Run the following command to get it solved:

autopep8 -i <filename>.py

This will update your code and solve all indentation errors :)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sharyar Vohra
  • 182
  • 1
  • 11
7

If you're writing Python using Sublime Text and are getting indentation errors,

Menu ViewIndentationConvert 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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Puneet Lamba
  • 755
  • 8
  • 15
  • oh ... so is sublime causing this ? – Nitin4873 Apr 30 '17 at 10:57
  • Yes, the issue I'm describing is caused by Sublime. 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. – Puneet Lamba May 04 '17 at 20:42
  • I had the same issue with notepad++. What met the eyes true so took sometime to crack this. I had to move the cursor one char at a time to figure out the editor had converted some whitespaces to tabs – Bharat Anand Feb 08 '18 at 01:54
5

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 EditpreferencesEditor.

Bottom line: use spaces, not tabs

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alex
  • 51
  • 1
  • 1
5

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!

WMoreland
  • 78
  • 1
  • 5
4

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.

Zoltán
  • 21,321
  • 14
  • 93
  • 134
  • key being that blank lines within the function definition are fine, _but_ they still must have the initial whitespace since Python interprets any blank line as the end of the function – MichaelChirico Jun 19 '17 at 01:45
3

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.

3

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jesus Rodriguez
  • 11,918
  • 9
  • 64
  • 88
3

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.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mohideen bin Mohammed
  • 18,813
  • 10
  • 112
  • 118
  • how will I run my a code. Will I have to remove the """ and """ and the print a.replace and run it normally? – chibole Dec 30 '17 at 10:24
  • no """ """ (triple quotes) refer your content rather than string. its required because your code might contain string which is single/double quotes so """ required. – Mohideen bin Mohammed Dec 30 '17 at 11:53
3

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)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
3

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

enter image description here

Unindent not expected

enter image description here

Expected expression

enter image description here

and in the first row

Unexpected indentation

enter image description here

Adding that pass would fix all of these four problems.

Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
2

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
HimalayanCoder
  • 9,630
  • 6
  • 59
  • 60
2

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]]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ashutosh Kumar
  • 301
  • 3
  • 10
2

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:

  1. Copy the tabs or spaces that are causing the error

  2. Do a find and replace in your IDE (usually Ctrl + H).

  3. 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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Robin Duong
  • 61
  • 1
  • 10
0

Check your brackets I've got this error because I forgot to close one bracket

print("some text"
pandas.do_something()
Wackaloon
  • 2,285
  • 1
  • 16
  • 33