When I compile the Python code below, I get
IndentationError: unindent does not match any outer indentation level
import sys
def Factorial(n): # Return factorial
result = 1
for i in range (1,n):
result = result * i
print "factorial is ",result
return result
Why?
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.
Try this:
import sys
def Factorial(n): # return factorial
result = 1
for i in range (1,n):
result = result * i
print "factorial is ",result
return result
print Factorial(10)
IMPORTANT:
Spaces are the preferred method - see PEP 8 Indentation and Tabs or Spaces?. (Thanks to #Siha for this.)
For Sublime Text users:
Set Sublime Text to use tabs for indentation:
View --> Indentation --> Convert Indentation to Tabs
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:
python -m tabnanny yourfile.py
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
gg=G
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
2) Go to Format -> Untabify Region
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).
Or - you have mixed space and tab characters
For Spyder users goto
Source > Fix Indentation
to fix the issue immediately
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
Press Enter
On Atom
go to
Packages > Whitespace > Convert Spaces to Tabs
Then check again your file indentation:
python -m tabnanny yourFile.py
or
>python
>>> help("yourFile.py")
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.
If you use colab, then you can do avoid the error by this commands.
< Ctrl-A >
< Tab >
< Shift-Tab >
It's all [tab] indentation convert to [space] indentation. Then OK.
Just a addition. I had a similar problem with the both indentations in Notepad++.
Unexcepted indentation
Outer Indentation Level
Go to ----> Search tab ----> tap on replace ----> hit the radio button Extended below ---> Now replace \t with four spaces
Go to ----> Search tab ----> tap on replace ----> hit the radio button Extended below ---> Now replace \n with nothing
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
class junk:
"""docstring is indented too much"""
def fun(): return
IndentationError: unindent does not match any outer indentation level
I'm using Sublime text in Ubuntu OS. To fix this issue go to
view -> Indentation -> convert indentation to tabs
It could be because the function above it is not indented the same way.
i.e.
class a:
def blah:
print("Hello world")
def blah1:
print("Hello world")
Since I realize there's no answer specific to spyder,I'll add one:
Basically, carefully look at your if statement and make sure all if, elif and else have the same spacing that is they're in the same line at the start like so:
def your_choice(answer):
if answer>5:
print("You're overaged")
elif answer<=5 and answer>1:
print("Welcome to the toddler's club!")
else:
print("No worries mate!")
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:
#!/usr/bin/python -tt
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.
for Atom Users, Packages ->whitspace -> remove trailing whitespaces
this worked for me
I had a function defined, but it did not had any content apart from its function comments...
def foo(bar):
# Some awesome temporary comment.
# But there is actually nothing in the function!
# D'Oh!
It yelled :
File "foobar.py", line 69
^
IndentationError: expected an indented block
(note that the line the ^ mark points to is empty)
--
Multiple solutions:
1: Just comment out the function
2: Add function comment
def foo(bar):
'' Some awesome comment. This comment could be just one space.''
3: Add line that does nothing
def foo(bar):
0
In any case, make sure to make it obvious why it is an empty function - for yourself, or for your peers that will use your code
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:
import sys
def Factorial(n): # Return factorial
result = 0
for i in range (1,n):
result = result * i
print "factorial is ",result
return result
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.
For example:
1. def convert_distance(miles):
2. km = miles * 1.6
3. return km
In this code same situation occurred for me. Just delete the previous indent spaces of
line 2 and 3, and then either use tab or space. Never use both. Give proper indentation while writing code in python.
For Spyder goto Source > Fix Indentation. Same goes to VC Code and sublime text or any other editor. Fix the indentation.
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.
I had the same error because of another thing, it was not about tabs vs. spaces. I had the first if slightly more indented than an else: much further down. If it is just about a space or two, you might oversee it after a long code block. Same thing with docstrings:
"""comment comment
comment
"""
They also need to be aligned, see the other answer on the same page here.
Reproducible with a few lines:
if a==1:
print('test')
else:
print('test2')
Throws:
File "<ipython-input-127-52bbac35ad7d>", line 3
else:
^
IndentationError: unindent does not match any outer indentation level
I actually get this in pylint from a bracket in the wrong place.
I'm adding this answer because I sent a lot of time looking for tabs.
In this case, it has nothing to do with tabs or spaces.
def some_instance_function(self):
json_response = self.some_other_function()
def compare_result(json_str, variable):
"""
Sub function for comparison
"""
json_value = self.json_response.get(json_str, f"{json_str} not found")
if str(json_value) != str(variable):
logging.error("Error message: %s, %s",
json_value,
variable) # <-- Putting the bracket here causes the error below
#) <-- Moving the bracket here fixes the issue
return False
return True
logging.debug("Response: %s", self.json_response)
# ^----The pylint error reports here
Im writing a new program for my friend,
and in a function I have a try and an except but if i run it, it gives me
an error :"File "main.py", line 19
try:
^
TabError: inconsistent use of tabs and spaces in indentation"
Im trying everything to fix it but it doesn't work...
The error that you are getting is fairly self-explanatory: TabError: inconsistent use of tabs and spaces in indentation simply means that you are using tabs in some places in your code and spaces in other places.
This can be a little difficult to diagnose as although two lines will appear to be the same level of indentation, one will be indented with a tab and the other with probably 3 or 4 spaces.
The reason this is important in Python, is that as I am sure you are aware, scopes are defined using indentation. So if you are not consistently using either tabs or spaces (as you most likely are), a TabError will be thrown!
If you are still unsure where you have used spaces instead of tabs (or the other way around), most text-editors will have the option to show white-space and tab allowing you to easily see where you've slipped up.
It is indeed very hard to distinguish spaces and tabs by our human beings! However, you can use Python IDLE GUI (in Windows) to Tabify (under Format) the whole file to make sure the indentation is consistent.
I know there are many questions on tabs vs. spaces, but it appears that, contrary to what PEP 0008 says about Python 3, mixing tabs and spaces is not always illegal. Specifically, mixing tabs and spaces in the same block is illegal, but blocks with spaces and blocks with tabs are allowed in the same file.
For example, this throws a TabError on Python 3.4:
for x in range(10):
print(x) # Spaces
print(x) # Tab
But this runs fine:
for x in range(10):
print(x) # Spaces
for y in range(5):
print(y) # Tab
Is this by design?
Edit: The question is not whether tabs are better than spaces. The question is whether Python's allowing tabs and spaces in the same file is by design.
The test for this is pretty simple (Lib/tests/test_exceptions.py):
self.raise_catch(TabError, "TabError")
try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n",
'<string>', 'exec')
except TabError: pass
else: self.fail("TabError not raised")
Looking at the code where this error is actually thrown (Parser/tokenizer.c, tok_get()) it looks like this merely compares the indentation kind to what the previous line used, and not what is used throughout the file.
The documentation says (Doc/reference/lexical_analysis.rst, emphasis mine)
Indentation is rejected as inconsistent if a source file mixes tabs and spaces in a way that makes the meaning dependent on the worth of a tab in spaces; a TabError is raised in that case.
It's okay to mix tabs and spaces if the "blocks" are completely "separated" by going back to indentation level 0; as there can be no confusion about the program's logic due to tab width settings. The problem with mixing tabs and spaces in Python is that Python assumes that a tab is eight spaces wide, but that the programmer's editor may use something else. For example, code like this:
def my_fun(i):
if i == 6:
foo()
------->bar() # Tab
Will be seen as this with a tabstop of 4:
def my_fun(i):
if i == 6:
foo()
bar()
Which is obviously not what the program does!
But in cases like:
def my_fun(i):
if i == 6:
foo()
bar()
def my_fun2(i):
--->if i == 7:
--->--->foo()
--->--->bar()
It's okay from a "logic" point of view as no matter how I view tabs, it's always clear what the logic is. It's of course still a bad idea to mix tabs and spaces in a single file, but that's merely a stylistic error, and not a logic error ;-)
So to answer the question: judging from that one line in the documentation, I
would say that this is by design. I can't find a PEP for this, though, and this
case isn't tested. I would be not rely on it that all Python versions in the
future behave the same!
Python tries to segment each little block of code so that when you copy and paste, it still works, and you aren't forced to make everything perfect. One of the many beauties of python.
PEP 8 is just a convention for the most readable code, and I recommend that you do follow it, but you don't have to
If you want to look for what PEP 8 encompasses there are several editors that will inspect your code for violations that are legal in python, but not nice. I use PyCharm. PyCharm doesn't like when you use spaces and tabs in the same file and it will get snarky with the squiggle under-linings.
This question already has answers here:
I'm getting an IndentationError. How do I fix it?
(6 answers)
Closed last month.
The following python code throws this error message, and I can't tell why, my tabs seem to be in line:
File "test.py", line 12
pass
^
TabError: inconsistent use of tabs and spaces in indentation
class eightPuzzle(StateSpace):
StateSpace.n = 0
def __init__(self, action, gval, state, parent = None):
StateSpace.__init__(self, action, gval, parent)
self.state = state
def successors(self) :
pass
You cannot mix tabs and spaces, according the PEP8 styleguide:
Spaces are the preferred indentation method.
Tabs should be used solely to remain consistent with code that is already indented with tabs.
Python 3 disallows mixing the use of tabs and spaces for indentation.
Python 2 code indented with a mixture of tabs and spaces should be converted to using spaces exclusively.
When invoking the Python 2 command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are highly recommended!
Using Visual Studio 2019
I was using tabs but the editor was inserting spaces and it would result in errors.
To avoid getting the spaces and tabs mixed up , set your preferences
Go to Edit->Advanced->Set Leading Whitespace->Tabs (or Whitespaces)
After I set it to Tabs, my tabs stop being represented as spaces and it worked fine thereafter
For linux nano users:
if your code includes 4 spaces instead of a tab, you should keep using 4 spaces or change all of them to a tab. If you use mixed it gives an error.
open your code in a text editor, highlight all of it (ctr+a) and go to format and select either "Tabify region" or "Untabify region". It'll just make all the indents have the same format.
not using the backspace also is important (especially in the Leafpad editor). If you want to decrease indent, use only Alt_key + TAB.
This should be done when you delete a line in a Python code.
I'm new to Python and it just confounds me with Indentation errors. In the following images, why does the first one work and the second one give me an indentation error?
Works:
Doesn't work: (Notice extra tree-expander that pops up in Notepad++)
Error:
File ".\sigma.py", line 14
for val in vs:
^
IndentationError: unexpected indent
I'm using Notepad++ and there are no spaces/tabs issues anywhere. Also, tried it out on the Python console typing it in exactly the same way in the 2nd image. It works fine. I'm guessing there's a very logical explanation to this, but coming from a strong-typed background (>5 years in Java), this feels like an unnecessary error.
You are mixing tabs and spaces. Don't do this, it creates inconsistent indentation problems.
Run your script through the tab checker:
python -tt script.py
and fix any and all tabs (replace with spaces), then configure your editor to only use spaces.
For Notepad++, see:
Convert tabs to spaces in Notepad++
How does one configure Notepad++ to use spaces instead of tabs?