Indentation errors in python [duplicate] - python

This question already has answers here:
IndentationError: unindent does not match any outer indentation level
(32 answers)
Closed 4 years ago.
I am doing python programming in notepad++ ,
so as suggested in many posts I have downloaded a tool called "python indent" and set it as enable.
Even after this , when I type in the print statement still I get the indentation errors such as "IndentationError: unindent does not match any outer indentation level" , any other tool is available for this purpose?
Because in javascript ,when I select the entire file and go to jshint tool and select indentation, I just get the properly indented file .
I am searching for a tool in python , but not able to get it. Anybody has any suggestions please?
edit:
try:
print "hi"
keys = mgt.get_keys(name)
I am getting the error after inserting print statement

Sounds like you have mixed tabs and spaces in your block. Use one or the other, but not both.

There is no way to auto-indent python without understanding the code (as #alKid and #Daniel say in the comments):
For example:
if(x < y):
# Since there are no ending brackets
# how will the program
# know when you want
# to exit the indentation block?

This is likely Notepad++ inserting tabs/spaces inconsistent with your existing code. I first suggest making the spaces/tabs visible; Menu item View / Show Symbol, then select "Show White Space and Tab". I suggest using this setting for any whitespace-significant language.
I find the default settings in Notepad++ (I'm using v.6.6.7) often mess up my Python indentation. To correct this: Settings / Preferences / Tab Settings / python; uncheck "use default value" and instead specify "Replace by space."

In Sublime Text 2 there is the option to auto indent using white spaces under View > Indentation > Indent Using Whitespaces. There is also the option to convert indentation to whitespaces or convert indentation to tabs under View > Indentation > Convert Indentation to Tabs.
I know this does not address notepad++ but it is possible notepad++ has something similar available and if not this may be helpful to Sublime Text 2 users.

Related

Pycharm sometimes does not indent the proper amount

I have tabs and indents|indent set to 2:
However the actual indentation is coming up as 3 - specifically inside the groupby function - which I have unindented and re-indented several times to be sure the behavior were consistent[-ly incorrect]:
Note that I have also tried the Auto-indent (Option-Command-I) - it also indents stuff to 3 spaces instead of 2. Bit strange..
Any thoughts?
The first thing you might want to check is to make sure you don't have Detect and use existing file indents for editing enabled in Settings/Preferences | Editor | Code Style. If you do, when you auto-indent, it might apply the wrong settings.
You can try to fix incorrectly formatted code by using Option+Command+L (Mac) / Control+Alt+L (PC), which is the Reformat Code option. That should fix the code and then auto-indent should work correctly.
This is most annoying problem in pycharm. Here is simple answer to this :
Just follow the path :
GO to Edit->Convert Indents->To Spaces
This will actually insert space instead of tabular character in empty space when you default enter for next line.

IndentationError when adding new line inside code [duplicate]

I am new to atom, so I opened my existing code using atom and modified few lines, then when I tried running the code with python, I get the following error:
IndentationError: unindent does not match any outer indentation level
I realized that Atom editor does indent my code differently to what I had. refer to the attached picture below showing the different indentation styles. line 1300 is the old indentation and 1301 is the one created by Atom
How can I fix this without modifying my 1000+ line code and so that atom uses the same style of indentation.
You have mixed tabs and spaces in your code. You should use spaces, always.
You can use this plugin to quickly fix your code, and please, use only spaces and 4 spaces for each level of indentation.
I had a similar error while using Atom,I fixed it using below steps.
Install notepad++
Open the file which has issue(one you have mentioned in question) in notepad++.
Go to View > Show Symbol > Show All Characters,this will show up where the tabs and where spaces are available.
Go to Edit->Blank Operations->TAB to Space to replace all tabs with spaces.
Go to View > Show Symbol > Show All Characters,confirm all tabs are replaced with spaces.
Save file and reload page,this will fix this issue.
In the newer versions of Atom, just go to settings > Editor; then scroll down to tab length and change it to 4; then change tab type to soft. This will make the tab key insert 4 spaces instead of a tab character moving forward. You still have to update your previous code using one of the above methods.
In the Atom Text Editor's top menu bar :
click the Packages tab
click Whitespace in the dropdown menu
Choose your preferred option (ie: Convert Spaces to Tabs)
And that will fix this pesky problem.

Pygame Error: TabError [duplicate]

This question already has answers here:
I'm getting an IndentationError. How do I fix it?
(6 answers)
Closed last month.
The following python code throws this error message, and I can't tell why, my tabs seem to be in line:
File "test.py", line 12
pass
^
TabError: inconsistent use of tabs and spaces in indentation
class eightPuzzle(StateSpace):
StateSpace.n = 0
def __init__(self, action, gval, state, parent = None):
StateSpace.__init__(self, action, gval, parent)
self.state = state
def successors(self) :
pass
You cannot mix tabs and spaces, according the PEP8 styleguide:
Spaces are the preferred indentation method.
Tabs should be used solely to remain consistent with code that is already indented with tabs.
Python 3 disallows mixing the use of tabs and spaces for indentation.
Python 2 code indented with a mixture of tabs and spaces should be converted to using spaces exclusively.
When invoking the Python 2 command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are highly recommended!
Using Visual Studio 2019
I was using tabs but the editor was inserting spaces and it would result in errors.
To avoid getting the spaces and tabs mixed up , set your preferences
Go to Edit->Advanced->Set Leading Whitespace->Tabs (or Whitespaces)
After I set it to Tabs, my tabs stop being represented as spaces and it worked fine thereafter
For linux nano users:
if your code includes 4 spaces instead of a tab, you should keep using 4 spaces or change all of them to a tab. If you use mixed it gives an error.
open your code in a text editor, highlight all of it (ctr+a) and go to format and select either "Tabify region" or "Untabify region". It'll just make all the indents have the same format.
not using the backspace also is important (especially in the Leafpad editor). If you want to decrease indent, use only Alt_key + TAB.
This should be done when you delete a line in a Python code.

Indentation error when using subprocess in Python 2.7

I have tried using a function defined using subprocess but I get an indentation error depending on where I put it on my code. A minimal example of my code is:
import subprocess
def runsafe(job,args):
jobs=[job];
for arg in args:
jobs.append(arg)
proc=subprocess.Popen(jobs,stdout=subprocess.PIPE)
return proc.stdout.readlines()
if __name__=="__main__":
runsafe("mkdir","Try")
A=0
B=7
This works and gives me the correct input (this code just creates three new folders called T, r, y where it's executed) but the indentation seems weird to me. A and B are just two constants that I will use later in the code.
For me the most natural would be to write:
import subprocess
def runsafe(job,args):
jobs=[job];
for arg in args:
jobs.append(arg)
proc=subprocess.Popen(jobs,stdout=subprocess.PIPE)
return proc.stdout.readlines()
if __name__=="__main__":
runsafe("mkdir","Try")
A=0
B=7
If I do this I just get:
IndentationError: 'unexpected indent'
Why is it necessary to indent (again) the line where I call runsafe? Shouldn't it work if I use it like in the second example?
You are very likely mixing tabs and spaces in your indentation. With Python 2 this often leads to weird behavior because mixing tabs and spaces actually works. But it doesn’t work in the way you would maybe expect: For Python 2, a tab is equivalent to 8 spaces. So for evaluating the indentation level, every tab is replaced by 8 spaces.
So when you have an indentation like this (where a . is a space, and ---→ is a tab):
def test():
........pass
---→pass
then it might look weird but it is valid since everything is indented using 8 spaces.
So you should make sure that you are using consistent indentation (it doesn’t matter whether it’s spaces or tabs—as long as it’s consistent).
Btw.: In Python 3 this is no longer allowed and will throw a syntax error (actually a TabError) with an actually helpful message: TabError: inconsistent use of tabs and spaces in indentation.
Your code mixes tabs and spaces for indentation. While this was possible and allowed in Python 2, Python 2 assumes tab size of 8 spaces. If you had an editor that has a setting to turn on visible whitespace, you'd see that one of the lines is indented with 8 spaces, and the other 2 with a single TAB:
if __name__=="__main__":
........runsafe("mkdir","Try")
--->A=0
--->B=7
That is, in your editor you had the tab display default to 4 spaces, while Python 2 expects 8 spaces to match a TAB.
As the tab size cannot be agreed on, yet in Python the indentation is significant, use of tabs for indentation is not considered best practice in either Python 2 or Python 3.
Tabs should be used solely to remain consistent with code that is already indented with tabs:
And mixing tabs and spaces in a way that makes indentation depend on the worth of a tab expressed in spaces is very wrong.
In Python 2 the tab size is 8, so indentation of TAB counts the same as 8 spaces or single TAB. Unfortunately there are many code editors that do not realize this, and instead use a different tab size for Python 2 code. In Python 3 OTOH, a TAB is only matched by another TAB. A good Python 3 editor would then mark inconsistent use of tabs in indent as syntax errors.
Thus the only consistent way of using tabs is using only tabs for indentation. In Python 2 there is a switch for that; you can start your Python interpreter with option -tt, or put it on the #! line after the python command, which will cause Python 2 to throw an error if it ever meets a line which makes the indent depend on tab size.
However, if you're writing new code, please be advised that the Python community almost uniformly follows the PEP 8 coding conventions: indentations are 4 spaces, and no tabs are used. In my experience, it is only the ever so odd legacy project that does not obey this guideline. Nearly all open-source projects these days that have coding conventions also require 4-space indentation, as well as other aspects of PEP 8.

SpeechRecognition as a function [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

Categories