Related
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
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
I'm trying to make a game in python, and stack trace keeps coming up with 'invalid syntax'(those are the EXACT words of the stack trace, not me summing it up) at this line:
print('Look(1) | Bust down door with weapon(2)')
The cursor is always between the 'p' and the 'o' whenever I check it with ALT+X, regardless of where it
was before I checked it.
There are no syntax errors in that line that I can recognize. I was wondering if someone more experienced could help me?
These are the lines above and below that in case you think it's not that line itself that's causing the
problem:
print('You are in a dark and grimy dungeon. You see no windows, and a door. What\
would you like to do?')
print('Look(1) | Bust down door with weapon(2)')
act_umpteenth = input('>>> ')
while act_umpteenth:
[rest of code continues on here that I'm not bothered to copy and paste]
Edit: Solution found. The culprit was a close bracket behind a string that I was assigning to a variable a few lines up. I think I thought it was a print statement or something. :P I deleted it, and now the code works 100%. Thanks for suggesting that I look over the code for indentation/tab/spaces problems, even if it wasn't the problem, because otherwise I wouldn't have spotted the actual problem.
I would just go and redo all your tabs. You can highlight all the code, and press Shift + Tab (you might have to do this multiple times) to back everything up to the left edge. Then you'll want to re-tab everything over in the proper way.
try running it with
python -tt myscript.py
you are probably mixing tabs and spaces when you run it with the -tt command it will tell you about inconsistent indentation
fixing your indentation should resolve your issue
I figured I would put this as an answer even though it is really a comment
OK, here's a piece of the script:
def start():
print "While exploring the ruins of a recently abandoned castle you stumble apon the entrance to what appears to be a dungeon. You are carrying on you a...
I keep getting the error
user#ubuntu:~/Documents/python$ python dungeon.py
File "dungeon.py", line 533
def start():
^
IndentationError: expected an indented block
I know this is probably obvious but does anyone have any clue as to what I'm doing wrong hear? I tried replacing the indent
with spaces only and tabs only but it still gives me this error. I appreciate any answers.
Make sure you aren't mixing tabs and spaces for indentation
Your string is missing a closing quote
Further, is def start() actually indented in your file? It isn't indented in this question, and that's what Python seems to be complaining about.
Looks like it expects def start(): to be indented. What does the code look like before that?
Check that whitespace is consistent (i.e. mixing tabs and spaces?).
If your editor supports, I suggest to make it expand all tabs to (4) spaces. This avoids such confusion, also when copy-pasting code.
In vim:
:se tabstop=4 shiftwidth=4 expandtab
:%retab
Are you sure there is a tab character in that position? Try open it with vi and add yourself the tab just to check is fine.
Try looking at the code just before that line. Is there an unfinished block (line ending with :)? If yes, put something in that block – a pass statement will do.
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