IndentationError: unindent does not match any outer indentation level - python

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

Related

IndentationError: unexpected indent error in python script for discord [duplicate]

How do I rectify the error "unexpected indent" in 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. 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.
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.
Run your code with the -tt option to find out if you are using tabs and spaces inconsistently.
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.
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.
Run the following command to get it solved:
autopep8 -i <filename>.py
This will update your code and solve all indentation errors :)
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.
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!
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
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.
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.
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.
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.
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.
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)
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.
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]]
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.

IndentationError: unindent does not match any outer indentation level ( line 51 cv2.putText(im,'% s - %.0f' %) [duplicate]

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

IndentationError: unindent does not match any outer indentation level even though my indentation is correct [duplicate]

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

Auto correct indentation errors in Python

I am trying fix some indentation errors in a Python script. Is there a way to auto correct the errors online or using other utilities?
I hope this error is very familiar, but wanted to avoid this again. Does any editor help in fixing these issues?
IndentationError: expected an indented block
It's not possible in general because some cases would be ambiguous:
something = foo()
if something:
something.bar()
print("ok") # Only half indented. Should this be inside or outside of the if statement?
It's much better to find an editor with auto-indentation support and make sure you indent properly (even in languages without significant whitespaces, as it makes your code easier to read).
You can use reindent.py
For me it worked on some files but it didin't work on others.Give it a try.
reindent.py
Uasge:
reindent.py <filename>.py
Change Python (.py) files to use 4-space indents and no hard tab characters.
Also trim excess spaces and tabs from ends of lines, and remove empty lines
at the end of files.
You can use Spyder IDE
Source Menu -> Fix Indentation
This particular error usually occurs when you forget to add an indented block after a statement that needs one (i.e. if or for). You likely forgot to indent the required block or accidentally hit backspace (or something) such as
def sayhello():
print "Hello world!"
Sometimes you don't want any code after an if statement or after try/except statements, but python will require at least one line after them, so you can use the pass keyword
try:
x= 4/0
except:
pass
print x

indentationError in if else loop

while i trying to execute following code
for value in jsondata:
command = value['command']
val = value['value']
print command
print val
if command=='sel_media':
t = find(dirpath + '\\' + myarg)
t1= capture(t.getX() - 50, t.getY() + 50, t.getW(), t.getH())
click(t1)
else:
print "else inside-----------"
am getting
else:
^
indentationError: unindent does not match any outer indentation level
i dont know why it is happening?
please correct me
Your code is probably mixing tabs and spaces for indentation.
Just set your editor to never use tabs. All decent programming editors have this option.
Please check all blanks in your file ans spaces not tab. If you have vim editor you can check by :set list command.
This is probably due having a tab in your code somewhere. Python treating tabs as 8 spaces, but your editor is probably set up to display them as 4 spaces. try using python -t which will give you an error if you use a tab character.
Set your code editor to use spaces instead of tabs and set those tabstops to 4. Python uses 4 spaces to differentiate between code blocks. Also you can try using sublime, it does this autoatically according to file types. You can also try to manually put 4 spaces and then wrtiting your code accordingly. Hope it helps.

Categories

Resources