How to debug indentation errors in python - python

I am trying to write my very first python script. This was working but then after some slight refactoring I have, apparently, broken the indentation. I can not determine what is the problem. The interpretor complains about the following method. Can someone point it out?
def dataReceived(self, data):
a = data.split(':')
print a
if len(a) > 1:
command = a[0]
content = a[1]
msg = ""
if command == "iam":
self.name = content
msg = self.name + " has joined"
elif command == "msg":
msg = self.name + ": " + content
print msg
The error reads: File "python_server.py", line 17
a = data.split(':')
^ IndentationError: expected an indented block

I encountered a similar problem using Sublime Text 2.
To solve, click on the "Tab Size" at the bottom of the editor, and choose "Convert Indentation to Tabs".

You start using a text editor that allows you to show indents, and you become consistent about using spaces instead of tabs, and you enforce that in your editor.

There are a great number of things you can do here:
Use an editor that can show control characters (like vi with set list).
Use a hex dumper program like od -xcb.
Just delete the white space at the start of that line and re-insert it (may want to check the preceding line as well).

if you're using the "Sublime Text 2" editor, then I found this answer helpful - it details how to turn on whitespace characters and also convert tabs to whitespaces
sublime-text-2-view-whitespace-characters

Try Editra - www.editra.org
Your code looks fine, syntax seems fine...your text editor may be creating your errors. Review your file with Editra to see/review indentation levels.
Editra saved my sanity - I thought I had correct syntax when viewing my script in Text Editors including Notepad++ with python indent plugin. However, when I would run the script, it would throw off indentation errors every time. I finally opened the script up in Editra, and I could see the problem. Notepad++ and other text editors did not show correct indentations/tabs/spaces. Editra showed errors e.g. unexpected spaces, tabs - which I was able to correct.
Editra will auto-indent your script [and show errors -tabs, spaces -that may not show up in other text editors].
If you have indent errors it will show up as blue underlined segment;
If you are writing script [adding/deleting lines] Editra will auto-indent the script.
**I would suggest opening your script and editing it in Editra.
Hope this helps!
Best of luck.
str8arrow

Related

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

TabError: inconsistent use of tabs and spaces in indentation. I can't spot where [duplicate]

This question already has answers here:
I'm getting an IndentationError. How do I fix it?
(6 answers)
Closed last month.
I'm trying to create an application in Python 3.2 and I use tabs all the time for indentation, but even the editor changes some of them into spaces and then print out "inconsistent use of tabs and spaces in indentation" when I try to run the program.
How can I change the spaces into tabs? It's driving me crazy.
import random
attraktioner = ["frittfall","bergodalbana","spökhuset"]
class Nojesfalt:
def __init__(self, attraktion):
self.val = attraktion
self.langd = 0
self.alder = 0
#längdgräns för fritt fall
def langdgrans(self):
print("")
self.langd = int(input("Hur lång är du i cm? "))
if self.langd < 140:
print("tyvärr, du är för kort, prova något annat")
return 0
elif self.langd >= 140:
print("håll dig hatten, nu åker vi!")
print(" ")
return 1
#åldersgräns för spökhuset
def aldersgrans(self):
print("")
self.alder = int(input("Hur gammal är du? "))
if self.alder < 10:
print("tyvärr, du är för ung, prova något annat")
return 0
elif self.alder >= 10:
print("Gå in om du törs!")
print(" ")
return 1
#åker attraktion frittfall lr bergodalbana
def aka(self):
print("")
print(self.val)
tal = random.randint(0,100)
if tal < 20:
print("åkturen gick åt skogen, bättre lycka nästa gång")
elif tal >= 20:
print("jabbadabbbadoooooooo")
return 1
#går i spökhuset
def aka1(self):
print("")
print(self.val)
tal = random.randint(0,100)
if tal < 20:
print("du är omringad av spöken och kan inte fortsätta") return 0
elif tal >= 20:
print("Buhuuuuuu, buuuhuuuu")
return 1
#programkod
print("Välkommen till nöjesfältet, vad vill du göra?")
print(" ")
while 1:
vald_attr = input("Vad vill du göra?\n1. frittfall\n2. bergodalbana\n3. spökhuset\n4. Avsluta\n")
if vald_attr == "1":
val = Nojesfalt(attraktioner[0])
if val.langdgrans() == 1:
val.aka()
elif vald_attr == "2":
val = Nojesfalt(attraktioner[1])
val.aka()
elif vald_attr == "3":
val = Nojesfalt(attraktioner[2])
if val.aldersgrans() == 1:
val.aka1()
elif vald_attr == "4":
break
Don't use tabs.
Set your editor to use 4 spaces for indentation.
Make a search and replace to replace all tabs with 4 spaces.
Make sure your editor is set to display tabs as 8 spaces.
Note: The reason for 8 spaces for tabs is so that you immediately notice when tabs have been inserted unintentionally - such as when copying and pasting from example code that uses tabs instead of spaces.
For VSCode users
Ctrl+Shift+P or View->Command Palette.
Type
>Convert Indentation to Spaces
press Enter.
Using the autopep8 command below fixed it for me:
autopep8 -i my_file.py
Documentation for autopep8 linked here.
With the IDLE editor you can use this:
Menu Edit → Select All
Menu Format → Untabify Region
Assuming your editor has replaced 8 spaces with a tab, enter 8 into the input box.
Hit select, and it fixes the entire document.
When using the sublime text editor, I was able to select the segment of my code that was giving me the inconsistent use of tabs and spaces in indentation error and select:
view > indentation > convert indentation to spaces
which resolved the issue for me.
It is possible to solve this problem using notepad++ by replacing Tabs with 4 Spaces:
Choose Search -> Find... or press Ctrl + F
Select the Replace tab
In the box named Search Mode choose Extended(\n, \r, \t, \0, \x...)
In the field Find what : write \t
In the field Replace with : press Space 4 times. Be sure that there is nothing else in this field.
Click on the button Replace All
Generally, people prefer indenting with space. It's more consistent across editors, resulting in fewer mismatches of this sort. However, you are allowed to indent with tab. It's your choice; however, you should be aware that the standard of 8 spaces per tab is a bit wide.
Concerning your issue, most probably, your editor messed up. To convert tab to space is really editor-dependent.
On Emacs, for example, you can call the method 'untabify'.
On command line, you can use a sed line (adapt the number of spaces to whatever pleases you):
sed -e 's;\t; ;' < yourFile.py > yourNedFile.py
If you are using Sublime Text for Python development, you can avoid the error by using the package Anaconda. After installing Anaconda, open your file in Sublime Text, right click on the open spaces → choose Anaconda → click on autoformat. Done. Or press Ctrl + Alt + R.
Sublime Text 3
In Sublime Text, WHILE editing a Python file:
Sublime Text menu > Preferences > Settings - Syntax Specific :
Python.sublime-settings
{
"tab_size": 4,
"translate_tabs_to_spaces": true
}
I recently had the same problem and found out that I just needed to convert the .py file's charset to UTF-8 as that's the set Python 3 uses.
BTW, I used 4-space tabs all the time, so the problem wasn't caused by them.
What I did when the same error popped up: Select everything (Str + A) and press Shift + Tab. So nothing was indented anymore. Now go back to the lines you want to have indented, and put it back how you want it.
It worked for me...
If you use ATOM:
Go to Menu: Packages --> WhiteSpace --> Convert all Tabs to Spaces
Try deleting the indents and then systematically either pressing tab or pressing space 4 times. This usually happens to me when I have an indent using the tab key and then use the space key in the next line.
Your problem is due to your editor limitations/configuration. Some editors provide you of tools to help with the problem by:
Converting tabs into spaces
For example, if you are using Stani's Python editor you can configure it to do it on saving.
Converting spaces into tabs
If you are using ActiveState Komodo you have a tool to 'tabify' your code. As others already pointed, this is not a good idea.
Eclipse's Pydev provides functions "Convert tabs to space-tabs" and "Convert space-tabs to tabs".
I use Notepad++ and got this error.
In Notepad++ you will see that both the tab and the four spaces are the same, but when you copy your code to Python IDLE you would see the difference and the line with a tab would have more space before it than the others.
To solve the problem, I just deleted the tab before the line then added four spaces.
There was a duplicate of this question from here but I thought I would offer a view to do with modern editors and the vast array of features they offer. With python code, anything that needs to be intented in a .py file, needs to either all be intented using the tab key, or by spaces. Convention is to use four spaces for an indentation. Most editors have the ability to visually show on the editor whether the code is being indented with spaces or tabs, which helps greatly for debugging. For example, with atom, going to preferences and then editor you can see the following two options:
Then if your code is using spaces, you will see small dots where your code is indented:
And if it is indented using tabs, you will see something like this:
Now if you noticed, you can see that when using tabs, there are more errors/warnings on the left, this is because of something called pep8 pep8 documentation, which is basically a uniform style guide for python, so that all developers mostly code to the same standard and appearance, which helps when trying to understand other peoples code, it is in pep8 which favors the use of spaces to indent rather than tabs. And we can see the editor showing that there is a warning relating to pep8 warning code W191,
I hope all the above helps you understand the nature of the problem you are having and how to prevent it in the future.
SOULUTION FOR SUBLIME TEXT
My Solution to this problem was to open it in idle editor and then idle editor will uncover your problem
e.g
SUBLIME TEXT
while run:
clock.tick(27)
milli = clock.tick()
seconds = milli/1000
timeForLevel += seconds
print(timeForLevel)
IDLE EDITOR
while run:
clock.tick(27)
milli = clock.tick()
seconds = milli/1000
timeForLevel += seconds
print(timeForLevel)
I am not saying that you should only use idle editor. I'm saying that if you get that error you should check idle editor
I had the same error. I had to add several code lines to an existing *.py file. In Notepad++ it did not work.
After adding the code lines and saving, I got the same error. When I opened the same file in PyCharm and added the lines, the error disappeared.
I oddly ran into a similar issue with one of my .py files. I simply opened the file in Pycharm and pressed Option+Command+L which correctly formats the file contents in one go.
I suspect I was having trouble because I coded this particular .py file through jupyter labs as opposed to my usual choice of sublime text or Pycharm and therefore ran into some hidden indentation issues many answers here have alluded to
Use pylint it will give you a detailed report about how many spaces you need and where.
The following trick has worked for me:
Copy and paste the code in the notepad.
Then from the notepad again select all and copy the code
Paste in my views.py
Select all the newly pasted code in the views.py and remove all the tabs by pressing shift+tab from the keyboard
Now use the tab key again to use the proper indentation
For Anaconda, Spyder users you can go to Source> Fix indentation
If your editor doesn't recognize tabs when doing a search and replace (like SciTE), you can paste the code into Word and search using Ctr-H and ^t which finds the tabs which then can be replace with 4 spaces.
Solving this using Vim editor
Open terminal (Ctrl + Alt + T).
Go to the directory where the file is located (cd <path_to_your_directory>). Ex: cd /home/vineeshvs/work.
Open the file in Vim (vim <file_name>). Ex: vim myfile.txt .
[Optional step] Enable search keyword highlighting in Vim (ESC :set hlsearch)
Go to the line where you have this problem (ESC :<line_number>). Ex: :53 in Vim editor after pressing ESC button once.
Replace tabs using the required number of spaces in Vim (:.,$s/\t/<give_as_many_spaces_as_you_want_to_replace_tab>/gc). Ex: Tab will be replaced with four spaces using the following command: :.,$s/\t/ /gc after pressing ESC button once). This process is interactive. You may give y to replace the tab with spaces and n to skip a particular replacement. Press ESC when you are done with the required replacements.
Well I had the same problem and I realised that the problem is that I copied code from another python editor to sublime.
I was working with jupyter notebook and then I copied the code into sublime. Apparently when you make specific modifications (like moving code in functions) then indentation gets messy and this is where the problem comes from.
So just stick to one editor. If you do so, then you will be having no problem.
For Jupyter users:
CTRL + Shift + P Automatically idents the selection:
While the original question is about self authored code, the search engines lead here for when searching for the title string. An error message one might very likely get when attempting to make use of an already existing library or tool.
For those finding their way here when attempting to use someone elses code; It is a python2 vs. python3 thing, according to Tab Error in Python (an answer which also refers to the relevant section of the PEP8 styleguide.
I got the same errors but could not figure out what I was doing wrong.
So I fixed it by running auto-indent on my code and allowing the machine to fix my fault.
If anyone is wondering how I did that.
Simple.
Go in vim.
Type in G=gg.
This will automatically fix everything. Good luck :)
Sometimes, tab does mess up while indenting. One way is to obviously use the tab and backspace to correctly indent the code.
Another way is to use space 4 times (depending on how much you want to indent).
A weird way that worked for me when nothing else worked, whichever line I getting the error, I backspaced that line to the previous line and then pressed enter. It automatically indented the line to correct position and I was not getting any error after that.
Hopefully, this should help.

I dont understand the improper uses of spaces and tabs in indentation error in my code [duplicate]

This question already has answers here:
I'm getting an IndentationError. How do I fix it?
(6 answers)
Closed last month.
I'm trying to create an application in Python 3.2 and I use tabs all the time for indentation, but even the editor changes some of them into spaces and then print out "inconsistent use of tabs and spaces in indentation" when I try to run the program.
How can I change the spaces into tabs? It's driving me crazy.
import random
attraktioner = ["frittfall","bergodalbana","spökhuset"]
class Nojesfalt:
def __init__(self, attraktion):
self.val = attraktion
self.langd = 0
self.alder = 0
#längdgräns för fritt fall
def langdgrans(self):
print("")
self.langd = int(input("Hur lång är du i cm? "))
if self.langd < 140:
print("tyvärr, du är för kort, prova något annat")
return 0
elif self.langd >= 140:
print("håll dig hatten, nu åker vi!")
print(" ")
return 1
#åldersgräns för spökhuset
def aldersgrans(self):
print("")
self.alder = int(input("Hur gammal är du? "))
if self.alder < 10:
print("tyvärr, du är för ung, prova något annat")
return 0
elif self.alder >= 10:
print("Gå in om du törs!")
print(" ")
return 1
#åker attraktion frittfall lr bergodalbana
def aka(self):
print("")
print(self.val)
tal = random.randint(0,100)
if tal < 20:
print("åkturen gick åt skogen, bättre lycka nästa gång")
elif tal >= 20:
print("jabbadabbbadoooooooo")
return 1
#går i spökhuset
def aka1(self):
print("")
print(self.val)
tal = random.randint(0,100)
if tal < 20:
print("du är omringad av spöken och kan inte fortsätta") return 0
elif tal >= 20:
print("Buhuuuuuu, buuuhuuuu")
return 1
#programkod
print("Välkommen till nöjesfältet, vad vill du göra?")
print(" ")
while 1:
vald_attr = input("Vad vill du göra?\n1. frittfall\n2. bergodalbana\n3. spökhuset\n4. Avsluta\n")
if vald_attr == "1":
val = Nojesfalt(attraktioner[0])
if val.langdgrans() == 1:
val.aka()
elif vald_attr == "2":
val = Nojesfalt(attraktioner[1])
val.aka()
elif vald_attr == "3":
val = Nojesfalt(attraktioner[2])
if val.aldersgrans() == 1:
val.aka1()
elif vald_attr == "4":
break
Don't use tabs.
Set your editor to use 4 spaces for indentation.
Make a search and replace to replace all tabs with 4 spaces.
Make sure your editor is set to display tabs as 8 spaces.
Note: The reason for 8 spaces for tabs is so that you immediately notice when tabs have been inserted unintentionally - such as when copying and pasting from example code that uses tabs instead of spaces.
For VSCode users
Ctrl+Shift+P or View->Command Palette.
Type
>Convert Indentation to Spaces
press Enter.
Using the autopep8 command below fixed it for me:
autopep8 -i my_file.py
Documentation for autopep8 linked here.
With the IDLE editor you can use this:
Menu Edit → Select All
Menu Format → Untabify Region
Assuming your editor has replaced 8 spaces with a tab, enter 8 into the input box.
Hit select, and it fixes the entire document.
When using the sublime text editor, I was able to select the segment of my code that was giving me the inconsistent use of tabs and spaces in indentation error and select:
view > indentation > convert indentation to spaces
which resolved the issue for me.
It is possible to solve this problem using notepad++ by replacing Tabs with 4 Spaces:
Choose Search -> Find... or press Ctrl + F
Select the Replace tab
In the box named Search Mode choose Extended(\n, \r, \t, \0, \x...)
In the field Find what : write \t
In the field Replace with : press Space 4 times. Be sure that there is nothing else in this field.
Click on the button Replace All
Generally, people prefer indenting with space. It's more consistent across editors, resulting in fewer mismatches of this sort. However, you are allowed to indent with tab. It's your choice; however, you should be aware that the standard of 8 spaces per tab is a bit wide.
Concerning your issue, most probably, your editor messed up. To convert tab to space is really editor-dependent.
On Emacs, for example, you can call the method 'untabify'.
On command line, you can use a sed line (adapt the number of spaces to whatever pleases you):
sed -e 's;\t; ;' < yourFile.py > yourNedFile.py
If you are using Sublime Text for Python development, you can avoid the error by using the package Anaconda. After installing Anaconda, open your file in Sublime Text, right click on the open spaces → choose Anaconda → click on autoformat. Done. Or press Ctrl + Alt + R.
Sublime Text 3
In Sublime Text, WHILE editing a Python file:
Sublime Text menu > Preferences > Settings - Syntax Specific :
Python.sublime-settings
{
"tab_size": 4,
"translate_tabs_to_spaces": true
}
I recently had the same problem and found out that I just needed to convert the .py file's charset to UTF-8 as that's the set Python 3 uses.
BTW, I used 4-space tabs all the time, so the problem wasn't caused by them.
What I did when the same error popped up: Select everything (Str + A) and press Shift + Tab. So nothing was indented anymore. Now go back to the lines you want to have indented, and put it back how you want it.
It worked for me...
If you use ATOM:
Go to Menu: Packages --> WhiteSpace --> Convert all Tabs to Spaces
Try deleting the indents and then systematically either pressing tab or pressing space 4 times. This usually happens to me when I have an indent using the tab key and then use the space key in the next line.
Your problem is due to your editor limitations/configuration. Some editors provide you of tools to help with the problem by:
Converting tabs into spaces
For example, if you are using Stani's Python editor you can configure it to do it on saving.
Converting spaces into tabs
If you are using ActiveState Komodo you have a tool to 'tabify' your code. As others already pointed, this is not a good idea.
Eclipse's Pydev provides functions "Convert tabs to space-tabs" and "Convert space-tabs to tabs".
I use Notepad++ and got this error.
In Notepad++ you will see that both the tab and the four spaces are the same, but when you copy your code to Python IDLE you would see the difference and the line with a tab would have more space before it than the others.
To solve the problem, I just deleted the tab before the line then added four spaces.
There was a duplicate of this question from here but I thought I would offer a view to do with modern editors and the vast array of features they offer. With python code, anything that needs to be intented in a .py file, needs to either all be intented using the tab key, or by spaces. Convention is to use four spaces for an indentation. Most editors have the ability to visually show on the editor whether the code is being indented with spaces or tabs, which helps greatly for debugging. For example, with atom, going to preferences and then editor you can see the following two options:
Then if your code is using spaces, you will see small dots where your code is indented:
And if it is indented using tabs, you will see something like this:
Now if you noticed, you can see that when using tabs, there are more errors/warnings on the left, this is because of something called pep8 pep8 documentation, which is basically a uniform style guide for python, so that all developers mostly code to the same standard and appearance, which helps when trying to understand other peoples code, it is in pep8 which favors the use of spaces to indent rather than tabs. And we can see the editor showing that there is a warning relating to pep8 warning code W191,
I hope all the above helps you understand the nature of the problem you are having and how to prevent it in the future.
SOULUTION FOR SUBLIME TEXT
My Solution to this problem was to open it in idle editor and then idle editor will uncover your problem
e.g
SUBLIME TEXT
while run:
clock.tick(27)
milli = clock.tick()
seconds = milli/1000
timeForLevel += seconds
print(timeForLevel)
IDLE EDITOR
while run:
clock.tick(27)
milli = clock.tick()
seconds = milli/1000
timeForLevel += seconds
print(timeForLevel)
I am not saying that you should only use idle editor. I'm saying that if you get that error you should check idle editor
I had the same error. I had to add several code lines to an existing *.py file. In Notepad++ it did not work.
After adding the code lines and saving, I got the same error. When I opened the same file in PyCharm and added the lines, the error disappeared.
I oddly ran into a similar issue with one of my .py files. I simply opened the file in Pycharm and pressed Option+Command+L which correctly formats the file contents in one go.
I suspect I was having trouble because I coded this particular .py file through jupyter labs as opposed to my usual choice of sublime text or Pycharm and therefore ran into some hidden indentation issues many answers here have alluded to
Use pylint it will give you a detailed report about how many spaces you need and where.
The following trick has worked for me:
Copy and paste the code in the notepad.
Then from the notepad again select all and copy the code
Paste in my views.py
Select all the newly pasted code in the views.py and remove all the tabs by pressing shift+tab from the keyboard
Now use the tab key again to use the proper indentation
For Anaconda, Spyder users you can go to Source> Fix indentation
If your editor doesn't recognize tabs when doing a search and replace (like SciTE), you can paste the code into Word and search using Ctr-H and ^t which finds the tabs which then can be replace with 4 spaces.
Solving this using Vim editor
Open terminal (Ctrl + Alt + T).
Go to the directory where the file is located (cd <path_to_your_directory>). Ex: cd /home/vineeshvs/work.
Open the file in Vim (vim <file_name>). Ex: vim myfile.txt .
[Optional step] Enable search keyword highlighting in Vim (ESC :set hlsearch)
Go to the line where you have this problem (ESC :<line_number>). Ex: :53 in Vim editor after pressing ESC button once.
Replace tabs using the required number of spaces in Vim (:.,$s/\t/<give_as_many_spaces_as_you_want_to_replace_tab>/gc). Ex: Tab will be replaced with four spaces using the following command: :.,$s/\t/ /gc after pressing ESC button once). This process is interactive. You may give y to replace the tab with spaces and n to skip a particular replacement. Press ESC when you are done with the required replacements.
Well I had the same problem and I realised that the problem is that I copied code from another python editor to sublime.
I was working with jupyter notebook and then I copied the code into sublime. Apparently when you make specific modifications (like moving code in functions) then indentation gets messy and this is where the problem comes from.
So just stick to one editor. If you do so, then you will be having no problem.
For Jupyter users:
CTRL + Shift + P Automatically idents the selection:
While the original question is about self authored code, the search engines lead here for when searching for the title string. An error message one might very likely get when attempting to make use of an already existing library or tool.
For those finding their way here when attempting to use someone elses code; It is a python2 vs. python3 thing, according to Tab Error in Python (an answer which also refers to the relevant section of the PEP8 styleguide.
I got the same errors but could not figure out what I was doing wrong.
So I fixed it by running auto-indent on my code and allowing the machine to fix my fault.
If anyone is wondering how I did that.
Simple.
Go in vim.
Type in G=gg.
This will automatically fix everything. Good luck :)
Sometimes, tab does mess up while indenting. One way is to obviously use the tab and backspace to correctly indent the code.
Another way is to use space 4 times (depending on how much you want to indent).
A weird way that worked for me when nothing else worked, whichever line I getting the error, I backspaced that line to the previous line and then pressed enter. It automatically indented the line to correct position and I was not getting any error after that.
Hopefully, this should help.

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