I'm new to Python and it just confounds me with Indentation errors. In the following images, why does the first one work and the second one give me an indentation error?
Works:
Doesn't work: (Notice extra tree-expander that pops up in Notepad++)
Error:
File ".\sigma.py", line 14
for val in vs:
^
IndentationError: unexpected indent
I'm using Notepad++ and there are no spaces/tabs issues anywhere. Also, tried it out on the Python console typing it in exactly the same way in the 2nd image. It works fine. I'm guessing there's a very logical explanation to this, but coming from a strong-typed background (>5 years in Java), this feels like an unnecessary error.
You are mixing tabs and spaces. Don't do this, it creates inconsistent indentation problems.
Run your script through the tab checker:
python -tt script.py
and fix any and all tabs (replace with spaces), then configure your editor to only use spaces.
For Notepad++, see:
Convert tabs to spaces in Notepad++
How does one configure Notepad++ to use spaces instead of tabs?
Related
I'm trying to get autopep8 work to properly indent Python code with 2 spaces instead of 4. I'm using VS Code with Python extension which uses autopep8 for formatting. I found here that autopep8 can be configured to use 2 spaces by
"python.formatting.autopep8Args": ["--indent-size=2"]
But it does not work for me.
My situation is like this. When I press enter, it correctly starts the next line with the same indentation as the previous line. Press enter after an open parenthesis, it correctly starts the new line with 2 more spaces. But when I paste or save (I have "editor.formatOnPaste" and "editor.formatOnSave" set to true), the annoying thing happened: all the 2-space indentation inside the parentheses became 4 (other 2-space indentation are unaffected). Why is it doing this and how can I make it 2 spaces everywhere?
====EDIT====
I found out that the pylint error Wrong hanging indentation (remove 2 spaces). [bad-continuation]. It's because my pylintrc has indent-after-paren=2. I'm wondering if autopep8 or other Python formatter can set this property?
I also had to include this in my array in settings.json, similar to yours.
"--ignore E121"
According to https://pypi.org/project/autopep8/, this setting ensures your indents are a multiple of 4. By not enforcing that, the configured tab size in VSCode is used.
E121 - Fix indentation to be a multiple of four.
That being said, your indentation is still "acceptable" according to pep8, so it actually will not change it to the 4 spaces you are expecting in your parens. I had to outdent mine one level, then when it ran again, it didn't change it.
Unfortunately this is actually just a workaround and it actually negatively affects other indention rules...
You can see in the code for pep8 that they hardcode the default tab size to be the "python way" (4 spaces) in:
https://github.com/hhatto/autopep8/blob/120537a051d7f3cbbb5c4ede19b9e515156bd3d1/autopep8.py#L104
That makes it look like the hanging indent is just not respecting the --indent-size option...
Adding --indent-size=2 --ignore=E121 worked for me.
had the same issue, here is the solution:
Navigate to library directory of your environment
Open autopep8.py
Search for "DEFAULT_INDENT_SIZE" and change it to 2
Im writing a new program for my friend,
and in a function I have a try and an except but if i run it, it gives me
an error :"File "main.py", line 19
try:
^
TabError: inconsistent use of tabs and spaces in indentation"
Im trying everything to fix it but it doesn't work...
The error that you are getting is fairly self-explanatory: TabError: inconsistent use of tabs and spaces in indentation simply means that you are using tabs in some places in your code and spaces in other places.
This can be a little difficult to diagnose as although two lines will appear to be the same level of indentation, one will be indented with a tab and the other with probably 3 or 4 spaces.
The reason this is important in Python, is that as I am sure you are aware, scopes are defined using indentation. So if you are not consistently using either tabs or spaces (as you most likely are), a TabError will be thrown!
If you are still unsure where you have used spaces instead of tabs (or the other way around), most text-editors will have the option to show white-space and tab allowing you to easily see where you've slipped up.
It is indeed very hard to distinguish spaces and tabs by our human beings! However, you can use Python IDLE GUI (in Windows) to Tabify (under Format) the whole file to make sure the indentation is consistent.
This question already has answers here:
I'm getting an IndentationError. How do I fix it?
(6 answers)
Closed last month.
The following python code throws this error message, and I can't tell why, my tabs seem to be in line:
File "test.py", line 12
pass
^
TabError: inconsistent use of tabs and spaces in indentation
class eightPuzzle(StateSpace):
StateSpace.n = 0
def __init__(self, action, gval, state, parent = None):
StateSpace.__init__(self, action, gval, parent)
self.state = state
def successors(self) :
pass
You cannot mix tabs and spaces, according the PEP8 styleguide:
Spaces are the preferred indentation method.
Tabs should be used solely to remain consistent with code that is already indented with tabs.
Python 3 disallows mixing the use of tabs and spaces for indentation.
Python 2 code indented with a mixture of tabs and spaces should be converted to using spaces exclusively.
When invoking the Python 2 command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are highly recommended!
Using Visual Studio 2019
I was using tabs but the editor was inserting spaces and it would result in errors.
To avoid getting the spaces and tabs mixed up , set your preferences
Go to Edit->Advanced->Set Leading Whitespace->Tabs (or Whitespaces)
After I set it to Tabs, my tabs stop being represented as spaces and it worked fine thereafter
For linux nano users:
if your code includes 4 spaces instead of a tab, you should keep using 4 spaces or change all of them to a tab. If you use mixed it gives an error.
open your code in a text editor, highlight all of it (ctr+a) and go to format and select either "Tabify region" or "Untabify region". It'll just make all the indents have the same format.
not using the backspace also is important (especially in the Leafpad editor). If you want to decrease indent, use only Alt_key + TAB.
This should be done when you delete a line in a Python code.
I 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.
Here is the code:
count = 0
i = 0
while count < len(newlist):
if newlist[i] == newlist[i+6] and newlist [i+6] != newlist [i+12]:
two1.append(newlist[i])
two1.append(newlist[i+1])
two1.append(newlist[i+2])
two1.append(newlist[i+3])
count=count+1
i=i+6
print two1
In the terminal, I get:
File "<stdin>", line 2
count=count+1; i=i+6
^
IndentationError: unexpected indent
In the learnpython.org editor, I get no error. Either way, two1 is printing as [], which is not what I want.
Your first line of code is indented, which is illegal, so the terminal is correct. Are you sure you haven't forgotten to paste a line from your source code?
There obviously is some program logic missing - newlist and two1 aren't defined anywhere, for instance.
There is a mixture of tab characters and spaces in your code (visible by selecting if you edit the post, not in the formatted output). Using tabs for indentation in Python is discouraged, and mixing tabs and spaces is even worse. From PEP8:
Never mix tabs and spaces.
The most popular way of indenting Python is with spaces only. The
second-most popular way is with tabs only. Code indented with a
mixture of tabs and spaces should be converted to using spaces
exclusively. When invoking the Python 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!
For new projects, spaces-only are strongly recommended over tabs. Most
editors have features that make this easy to do.
Set up your editor to convert tabs to spaces, and life will be better.
Your program can't start on an indent.
About Scope:
http://beastie.cs.ua.edu/cs150/book/index_13.html