Inconsistent use of tabs and spaces in indentation - python

def contains_sequence(dna1, dna2):
''' (str, str) -> bool
Return True if and only if DNA sequence dna2 occurs in the DNA sequence
dna1.
>>> contains_sequence('ATCGGC', 'GG')
True
>>> contains_sequence('ATCGGC', 'GT')
False
'''
b=False
len2=len(dna2)
i=0
for j in dna1:
temp=dna1[i:i+len2]
if temp == dna2:
b=True
i=i+1
return b
I am new to Python. The program pasted above gives me an error "Inconsistent use of tabs and spaces in indentation" at line "if temp == dna2:" specifically. Can someone please help me out in finding out how the indentation is incorrect?

It means you have mixed up spaces and tabs in the indentation. You have to fix that to be consistent with either tabs or spaces.

If you look carefully at the lines
temp=dna1[i:i+len2]
if temp == dna2:
in your code, you will see that the "space" at the beginning of each line is "constructed" differently. In one case it uses tabs and in the other spaces, or, if both have tabs and spaces then they are used in different combinations.
You can examine this by placing your cursor at the beginning of each line and using the right-arrow key to "walk" your way through the characters. You'll see that the cursor moves differently on each line.
To fix, delete the tabs and spaces at the beginning of each line and re-insert them with the same characters on each line.
To avoid in the future, train yourself to use only the tab key OR the space key to indent, and consider setting your editor to automatically convert tabs to spaces.

Assuming you have a "good" IDE, it's best to set the tab key to make 4 spaces instead of a "tab", that way you have less problems, and it's good practice, for when you will work with other people.

I was almost struct at this problem for quiet some time. I was using CentOS Ec2 and found out that you can:
vim <filename>
Press Escape Key If you're in write/insert mode
:set list
The spaces will be visible as End Of Lines such as $ symbol.
It's helpful.

In my case Visual Studio code ..
Ctrl+Shift+P or View->Command Palette.
Type
Convert Indentation to Spaces
press Enter.

According to the your Doc strings
your code:
b=False
len2=len(dna2)
i=0
for j in dna1:
temp=dna1[i:i+len2]
if temp == dna2:
b=True
i=i+1
return b
This much Big code can be simplified to one line
return dna1.find(dna2)>=0
Also if u are not good with indentations in 'vim' editor its good to practice in IDLE3

If you are copying and pasting code from another source, always copy and paste it on a normal text editor first, then fix the indentation after copying and pasting it in a code editor. This is an easy way to fix this issue.

Related

I'm getting this error "IndentationError: unexpected indent" [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: expected an indented block when only using tabs? [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.

Matching indentation level according to PEP8/flake8

The question is how to properly break lines according to PEP8 while using TABs.
So here is a related question How to break a line in a function definition in Python according to PEP8. But the issue is that this only works properly when the length of the definition header def dummy( is an integer multiple of the tab length.
def tes(para1=x,
--->--->para2=y)
Otherwise I end up with a new error and flake8 complains about Error E127 or E128 because the its either over- or under-indented like this:
Under-indented E128
def test(para1=x,
--->--->para2=y)
Over-indented
def te(para1=x,
--->--->para2=y)
A solution where flake8 does not complain is to do:
def test(
--->--->para1=x,
--->--->para2=y
--->--->)
However, when I am programming I don't necessarily know in advance how many parameters I'm gonna use in that test() function. So once I hit the line limit I have rearrange quite a bit.
This obviously does apply to all continuations. Does this mean the cleanest solution is to break the line as soon as possible for every line which final length cannot be said by the time of first writing, or is there another solution.
Tab and space shall not be mixed for the solution.
So now I ask myself what is the legis artis to deal with line continuations?
I'm turning my original comment into an official answer.
The PEP-0008 has a section about whether to use Tabs or Spaces, quoted below (with my emphasis):
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!
You're running into issues with tabs, and you don't say whether you're using Python2 or 3, but I'd suggest you stick to the PEP-0008 guidelines.
You should replace tab chars in the file/module with 4 spaces and use spaces exclusively when indenting.
WARNING: Be very careful if you plan to use shell commands to do this for you, as some commands can be dangerous and mangle intended tab chars within strings (i.e. not only indentation tabs) and can break other things, such as repositories -especially if the command is recursive.
PEP8 is very clear:
Tabs or Spaces?
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 [emphasis added] mixing the use of tabs and spaces for indentation.
Reference: python.org.
So if you're writing new code and want to adhere to standards, just use spaces.

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

how to indent block of python code without using tabs

I am just learning python and need to know how to indent a block of code without using the tab button (because, as I have read, tab should not be used).
Example:
in a simple print function
def test(string):
print(string)
print("'" + string + "'")
test('test')
IF now, I want to put the print functions in an if statement
def test(string):
if len(string) > 2:
print(string)
print("'" + string + "'")
test('test')
How can I indent the two print statements without using the 'tab', or having to click on every line and insert 4 spaces? I am very used to selecting all the lines I need to move to the right and pressing tab regardless of program (geany, ipython, notepad++).
I would like to set off following the PEP8 style guide from the introduction into Python.
My concern is not this particular example, but if I have a code block I want to move left or right that is many more lines.
Thanks,
Ivan
It depends on what text editor you're using. I use Notepad++, which is one of the ones you mention, and it has an option to use spaces in place of tabs. So I just enable that for .py files, then I can indent a block by hitting tab exactly as you're used to (and unindent with shift-tab).
Go to settings > preferences > tab settings, select "python" from the list on the right and check the "replace by space" checkbox. Other text editors that offer the same feature will presumably each have their own way of enabling it, and their own way of making it language-specific.
Be aware that pressing tab to change the indentation of a selection is just a UI convention, albeit a common one. It doesn't work for example in Notepad, where hitting tab while text is highlighted behaves the same as typing anything else: replaces the selection with a tab. If you were using Notepad then I'm pretty sure the answer would be "it's not possible". If you use lots of different editors then I think unfortunately you're going to have to investigate each one in turn.
As you have mentioned, PEP8 recommends four spaces for each level of indentation. Many text editors allow you to set tabs to be replaced by a certain number of spaces. So in many cases it is still ok to use tab to program in python, just make sure that it is replaced by four spaces.
I personally use Sublime Text and there seems to be an option to customize Tabs:
{
"tab_size": 4,
"translate_tabs_to_spaces": true
}
In the Packages/User/Preferences.sublime-settings. Maybe worth trying that.

Categories