Asking user for input for a lists [duplicate] - python

I have a Python script:
if True:
if False:
print('foo')
print('bar')
However, when I attempt to run my script, Python raises an IndentationError:
File "script.py", line 4
print('bar')
^
IndentationError: unindent does not match any outer indentation level
I kept playing around with my program, and I was able to produce four errors in total:
IndentationError: unexpected indent
IndentationError: expected an indented block
TabError: inconsistent use of tabs and spaces in indentation
IndentationError: unindent does not match any outer indentation level
What do these errors mean? What am I doing wrong? How can I fix my code?
Note: This is an attempt at a canonical question because I see many similar posts every month. This is not a duplicate of existing questions about unindents or unexpected indents because they only deal with one type of indentation error each, and I'm looking to cover them all in one place.
It's also possible to have logically incorrect indentation that does not cause an error message. One common form of this is attaching else: to a for or while loop rather than (as intended) the corresponding if:. See Else clause on Python while statement if you need to close questions where OP did that.

Why does indentation matter?
In Python, indentation is used to delimit blocks of code. This is different from many other languages that use curly braces {} to delimit blocks such as Java, Javascript, and C. Because of this, Python users must pay close attention to when and how they indent their code because whitespace matters.
When Python encounters a problem with the indentation of your program, it either raises an exception called IndentationError or TabError.
A little history
The historical reasons for why Python uses indentation vs the arguably more commonly accepted curly braces {} is outlined in an article of the history of Python by Guido van Rossum - the creator of Python:
Python’s use of indentation comes directly from ABC, but this idea didn’t originate with ABC--it had already been promoted by Donald Knuth and was a well-known concept of programming style. (The occam programming language also used it.) However, ABC’s authors did invent the use of the colon that separates the lead-in clause from the indented block. After early user testing without the colon, it was discovered that the meaning of the indentation was unclear to beginners being taught the first steps of programming. The addition of the colon clarified it significantly: the colon somehow draws attention to what follows and ties the phrases before and after it together in just the right way.
How do I indent my code?
The basic rule for indenting Python code (considering that you treat the entire program as a "basic block") is: The first statement in a basic block, and each subsequent statement after it must be indented by the same amount.
So technically the following Python program is correct:
def perm(l):
# Compute the list of all permutations of l
if len(l) <= 1:
return [l]
r = []
for i in range(len(l)):
s = l[:i] + l[i+1:]
p = perm(s)
for x in p:
r.append(l[i:i+1] + x)
return r
However, as you can probably tell from above, randomly indenting your code makes is extremely hard to read and follow the flow of the program. It's better to be consistent and follow a style.
PEP 8 -- the Python style guide -- says:
Use 4 spaces per indentation level.
That is, each statement that is starting a new block and each subsequent statement in the new block, should be indented four spaces from the current indentation level. Here is the above program indented according to the PEP8 style guide:
def perm(l):
# Compute the list of all permutations of l
if len(l) <= 1:
return [l]
r = []
for i in range(len(l)):
s = l[:i] + l[i+1:]
p = perm(s)
for x in p:
r.append(l[i:i+1] + x)
return r
Can I still use tabs?
Python realizes that some people still prefer tabs over spaces and that legacy code may use tabs rather than spaces, so it allows the use of tabs as indentation. PEP8 touches on this topic:
Spaces are the preferred indentation method.
Tabs should be used solely to remain consistent with code that is already indented with tabs.
Note however the one big caveat is not to use both tabs and spaces for indentation. Doing so can cause all kinds of strange hard to debug indentation errors. Python expands tabs to the next 8th column, but if your editor is set to a tab size of 4 columns, or you you use spaces as well as tabs, you can easily produce indented code that looks fine in your editor, but Python will refuse to run. The Python 3 compiler explicitly rejects any program containing an ambiguous mixture of tabs and spaces, usually by raising a TabError. However, by default, mixing tabs and spaces is still allowed in Python 2, but it is highly recommended not to use this "feature". Use the -t and -tt command line flags to force Python 2 to raise a warning or (preferably) an error respectively. PEP8 also discusses this topic:
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!
What does "IndentationError: unexpected indent" mean?
Problem
This error occurs when a statement is unnecessarily indented or its indentation does not match the indentation of former statements in the same block. For example, the first statement in the program below is unnecessarily indented:
>>> print('Hello') # this is indented
File "<stdin>", line 1
print('Hello') # this is indented
^
IndentationError: unexpected indent
In this example, the can_drive = True line in the if block does not match the indentation of any former statement:
>>> age = 10
>>> can_drive = None
>>>
>>> if age >= 18:
... print('You can drive')
... can_drive = True # incorrectly indented
File "<stdin>", line 3
can_drive = True # incorrectly indented
^
IndentationError: unexpected indent
Fix
The fix for this error is to first make sure the problematic line even needs to be indented. For example, the above example using print can be fixed simply be unindenting the line:
>>> print('Hello') # simply unindent the line
Hello
However, if you are sure the line does need to be indented, the indentation needs to match that of a former statement in the same block. In the second example above using if, we can fix the error by making sure the line with can_drive = True is indented at the same level as the former statements in the if body:
>>> age = 10
>>> can_drive = None
>>>
>>> if age >= 18:
... print('You can drive')
... can_drive = True # indent this line at the same level.
...
What does "IndentationError: expected an indented block" mean?
(This might also occur as SyntaxError: unexpected EOF while parsing in Python 3.8 or lower.)
Problem
This error occurs when Python sees the 'header' for a compound statement, such as if <condition>: or while <condition>: but the compound statement's body or block is never defined. For example in the code below we began an if statement, but we never define a body for the statement:
>>> if True:
...
File "<stdin>", line 2
^
IndentationError: expected an indented block
In this second example, we began writing a for loop, but we forget to indent the for loop body. So Python still expects an indented block for the for loop body:
>>> names = ['sarah', 'lucy', 'michael']
>>> for name in names:
... print(name)
File "<stdin>", line 2
print(name)
^
IndentationError: expected an indented block
Comments don't count as bodies:
>>> if True:
... # TODO
...
File "<stdin>", line 3
^
IndentationError: expected an indented block
Fix
The fix for this error is to simply include a body for the compound statement.
As shown above, a common mistake by new users is that they forget to indent the body. If this is the case, make sure each statement meant to be included in the compound statement's body is indented at the same level under the compound statement's beginning. Here is the above example fixed:
>>> names = ['sarah', 'lucy', 'michael']
>>> for name in names:
... print(name) # The for loop body is now correctly indented.
...
sarah
lucy
michael
Another common case is that, for some reason, a user may not want to define an actual body for the compound statement, or the body may be commented out. In this case, the pass statement can be used. The pass statement can be used anywhere Python expects one or more statements as a placeholder. From the documentation for pass:
pass is a null operation — when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:
def f(arg): pass # a function that does nothing (yet)
class C: pass # a class with no methods (yet)
Here is the above example with the if statement fixed by using the pass keyword:
>>> if True:
... pass # We don't want to define a body.
...
>>>
What does "IndentationError: unindent does not match any outer indentation level" mean?
Problem
This error occurs when you unindent a statement, but now the indentation level of that statement does not match that of any former statement. For example, in the below code we unindent the second call to print. However, the indentation level does not match that of any former statement:
>>> if True:
... if True:
... print('yes')
... print()
File "<stdin>", line 4
print()
^
IndentationError: unindent does not match any outer indentation level
This error is especially hard to catch because even one space will cause your code to fail.
Fix
The fix is to ensure that when you unindent a statement, the indentation level matches that of a former statement. Consider the above example once again. In the example, I want the second call to print to be in the first if statements body. So I need to make sure that that line's indentation level matches that of the former statements in the first if statement's body:
>>> if True:
... if True:
... print('yes')
... print() # indentation level now matches former statement's level.
...
yes
>>>
I'm still getting an IndentationError but my program appears to be correctly indented. What do I do?
If your program visually appears to have correct indentation, but your still getting an IndentationError you have most likely mixed tabs with spaces. This will sometimes cause Python to raises strange errors. See the subsection Special cases under What does "TabError: inconsistent use of tabs and spaces in indentation" mean? for an more in-depth explanation of the problem.
What does "TabError: inconsistent use of tabs and spaces in indentation" mean?
Problem
This error only occurs when you attempt to mix tabs and spaces as indentation characters. As said above, Python will not allow your program to contain a mix of tabs and spaces, and will raise the specific exception TabError if it finds you have. For example, in the program below, a mix of tabs and spaces is used for indentation:
>>> if True:
... if True:
... print()
... print()
... print()
File "<stdin>", line 5
print()
^
TabError: inconsistent use of tabs and spaces in indentation
Here is a picture which visually shows the whitespace in the above program. Gray dots are spaces, and gray arrows are tabs:
We can see we have indeed mixed spaces and tabs for indentation.
Special cases
Note Python will not always raise a TabError if you mix tabs and spaces into your program. If the program indentation is unambiguous, Python will allow tabs and spaces to be mixed. For example:
>>> if True:
... if True: # tab
... pass # tab, then 4 spaces
...
>>>
And sometimes Python simply chokes on the mixture of tabs and spaces and erroneously raises an IndentationError exception when a TabError would be more appropriate. Another example:
>>> if True:
... pass # tab
... pass # 4 spaces
File "<stdin>", line 3
pass # 4 spaces
^
IndentationError: unindent does not match any outer indentation level
As you can see, running your code this way can create mysterious errors. Even though the program visually appears to be fine, Python became confused trying to parse the tabs and spaces used for indention and errored out.
These are excellent examples that demonstrate why to never mix tabs and spaces and make use of the -t and -tt interpreter flags when using Python 2.
Fix
If your program is short, probably the easiest and quickest fix is to simply re-indent the program. Make sure each statement is indented by four spaces per indention level (see How do I indent my code?).
However, if you already have a large program that you've mixed tabs and spaces into, there are automated tools that can be used to convert all of your indentation to just spaces.
Many editors such as PyCharm and SublimeText have options to automatically convert tabs to spaces. There are also several on-line tools such as Tabs To Spaces or Browserling that allow you to quickly re-indent your code. There are also tools written in Python. autopep8 for example can automatically re-indent your code and fix other indentation errors as well.
Even the best tools though will sometimes not be able to fix all of your indentation errors and you'll have to fix them manually. That's why it's important to always properly indent your code from the start.
A note about "SyntaxError" related indentation problems
Although not often, sometimes certain SyntaxError exceptions are raised due to incorrect indentation. For example, look at the code below:
if True:
pass
pass # oops! this statement should be indented!.
else:
pass
When the above code is run, a SyntaxError is raised:
Traceback (most recent call last):
File "python", line 4
else:
^
SyntaxError: invalid syntax
Although Python raises a SyntaxError, the real problem with the above code is that the second pass statement should be indented. Because the second pass isn't indented, Python doesn't realize that the previous if statement and the else statement are meant to be connected.
The fix for this type of error is to simply correctly re-indent your code. To see how to properly indent your code, see the section How do I indent my code?.
I'm still having a hard time with Python's indentation syntax. What do I do?
Don't get discouraged if you're still struggling. It can take time to get use to
Python's whitespace syntax rules. Here are some tips to help:
Get an editor that will tell you when you have an indentation error. Some goods ones are as said above are, PyCharm, SublimeText, and Jupyter Notebook.
When you indent your code, count out loud to yourself how many times you press the space-bar (or tab key). For example, if you needed to indent a line by four spaces, you would say out loud "one, two, three, four" while simultaneously pressing the space-bar each time. It sounds silly, but it helps train your brain to think about how deep you're indenting your code.
If you have an editor, see if it has an option to automatically convert tabs to spaces.
View others' code. Browse github or Stackoverflow and see examples of Python code.
Just write code. That's the single best way to get better. The more you write Python code, the better you'll get.
Resources used
https://en.wikipedia.org/
https://docs.python.org/3/
http://python-history.blogspot.com/2009/02/early-language-design-and-development.html
https://www.python.org/dev/peps/pep-0008/

Sublime Text 3
If it happens that you code in Sublime Text 3, this could help you with indentations problemes
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
}

You see, you have a tiny error.
if True:
if False:
print('foo')
print('bar')
You were supposed to do:
if True:
if False:
print('foo')
print('bar')
As you can see your print is only indented 3 spaces, it is supposed to be indented 4 spaces.

Historical note for Python 2
By default, Python 2 allowed tabs and spaces to be mixed, and would not produce an error by default. Passing the -tt option to Python 2.x causes it to raise an exception in the same cases that 3.x does, and -t causes a warning instead. The full details are explained at Python's interpretation of tabs and spaces to indent.
Note in particular that tabs are treated as 8 spaces (rather, they effectively increase the number of perceived spaces up to the next multiple of 8). Thus, if you were displaying the code with a standard 4-space indent, but have mixed spaces and tabs, you could end up with code that satisfies the indentation rules, but is not considered to be indented the same way that it looks.
As a result, you could get all kinds of other errors. For example:
# in 2.x
def example():
def nested(): # suppose this is indented with a tab
x = [1] # and this with two tabs
print x[0] + 1 # but this with 8 spaces instead of a tab
nested()
(Note that Stack Overflow's Markdown rendering will show the indentation as spaces even if I use tabs.)
That gives a NameError, since print x is no longer inside the nested function and x is out of scope in the outer example. Similarly, we could easily create a TypeError by giving example a local x = 1, or ValueError by giving it a local x = [].

Quick checklist
Incorrect indentation most commonly results in IndentationError, but it can also result in TabError (a sub-type of IndentationError) or SyntaxError (the indentation itself was legal, but it caused other code to have a syntax error). Indentation that is valid for Python code, but wrong for the programmer's intent, causes logical errors (the code doesn't raise an exception, but does something wrong).
It is strongly recommended not to use tabs for indentation. In 2.x, running Python with the -tt command line argument causes it to raise the same TabError, which is useful for finding problems.
The community standard, laid out in PEP 8, is to use four spaces per level of indentation.
Statements like if, for, def and class that end with a colon :, need an indented block after them:
if x:
do_y() # <- this must be indented
Blocks cannot be empty. Use the pass statement if nothing should happen:
if x:
pass # this statement does nothing, except make the block non-empty
Code within a block must have the same indentation:
if x:
do_y()
do_z() # this needs to line up with do_y()
The first line of code that lines up with the opening statement, or a lower level of indentation, is outside the block:
if x:
do_y()
do_z() # this happens regardless of the x value
# cannot write `else`: here; that is a syntax error
for i in range(10):
if x:
do_y()
do_z() # both the `if` and `for` blocks are ended
Python interprets tabs as expanding to the next 8th column; but in 3.x, indentation that mixes spaces and tabs must have the exact same pattern to count as the same indentation (and to indent further requires having the same pattern as a prefix). Failure to get this right results in TabError.
while and for loops in Python may have an else clause, which executes if the loop complete normally rather than via break. This is a common source of logical errors:
for i in range(10):
if i % 2:
print(f'{i} is odd')
else: # wrongly indented
print(f'{i} is even') # only happens once, and claims 9 is even!

Quick fix for Sublime users:
Press Ctrl-H to access Find and Replace
In Find: Type 4 spaces
In Replace: Copy and paste a tab from somewhere in your code
Click Replace All

Related

Unexpected indent in python [duplicate]

I have a Python script:
if True:
if False:
print('foo')
print('bar')
However, when I attempt to run my script, Python raises an IndentationError:
File "script.py", line 4
print('bar')
^
IndentationError: unindent does not match any outer indentation level
I kept playing around with my program, and I was able to produce four errors in total:
IndentationError: unexpected indent
IndentationError: expected an indented block
TabError: inconsistent use of tabs and spaces in indentation
IndentationError: unindent does not match any outer indentation level
What do these errors mean? What am I doing wrong? How can I fix my code?
Note: This is an attempt at a canonical question because I see many similar posts every month. This is not a duplicate of existing questions about unindents or unexpected indents because they only deal with one type of indentation error each, and I'm looking to cover them all in one place.
It's also possible to have logically incorrect indentation that does not cause an error message. One common form of this is attaching else: to a for or while loop rather than (as intended) the corresponding if:. See Else clause on Python while statement if you need to close questions where OP did that.
Why does indentation matter?
In Python, indentation is used to delimit blocks of code. This is different from many other languages that use curly braces {} to delimit blocks such as Java, Javascript, and C. Because of this, Python users must pay close attention to when and how they indent their code because whitespace matters.
When Python encounters a problem with the indentation of your program, it either raises an exception called IndentationError or TabError.
A little history
The historical reasons for why Python uses indentation vs the arguably more commonly accepted curly braces {} is outlined in an article of the history of Python by Guido van Rossum - the creator of Python:
Python’s use of indentation comes directly from ABC, but this idea didn’t originate with ABC--it had already been promoted by Donald Knuth and was a well-known concept of programming style. (The occam programming language also used it.) However, ABC’s authors did invent the use of the colon that separates the lead-in clause from the indented block. After early user testing without the colon, it was discovered that the meaning of the indentation was unclear to beginners being taught the first steps of programming. The addition of the colon clarified it significantly: the colon somehow draws attention to what follows and ties the phrases before and after it together in just the right way.
How do I indent my code?
The basic rule for indenting Python code (considering that you treat the entire program as a "basic block") is: The first statement in a basic block, and each subsequent statement after it must be indented by the same amount.
So technically the following Python program is correct:
def perm(l):
# Compute the list of all permutations of l
if len(l) <= 1:
return [l]
r = []
for i in range(len(l)):
s = l[:i] + l[i+1:]
p = perm(s)
for x in p:
r.append(l[i:i+1] + x)
return r
However, as you can probably tell from above, randomly indenting your code makes is extremely hard to read and follow the flow of the program. It's better to be consistent and follow a style.
PEP 8 -- the Python style guide -- says:
Use 4 spaces per indentation level.
That is, each statement that is starting a new block and each subsequent statement in the new block, should be indented four spaces from the current indentation level. Here is the above program indented according to the PEP8 style guide:
def perm(l):
# Compute the list of all permutations of l
if len(l) <= 1:
return [l]
r = []
for i in range(len(l)):
s = l[:i] + l[i+1:]
p = perm(s)
for x in p:
r.append(l[i:i+1] + x)
return r
Can I still use tabs?
Python realizes that some people still prefer tabs over spaces and that legacy code may use tabs rather than spaces, so it allows the use of tabs as indentation. PEP8 touches on this topic:
Spaces are the preferred indentation method.
Tabs should be used solely to remain consistent with code that is already indented with tabs.
Note however the one big caveat is not to use both tabs and spaces for indentation. Doing so can cause all kinds of strange hard to debug indentation errors. Python expands tabs to the next 8th column, but if your editor is set to a tab size of 4 columns, or you you use spaces as well as tabs, you can easily produce indented code that looks fine in your editor, but Python will refuse to run. The Python 3 compiler explicitly rejects any program containing an ambiguous mixture of tabs and spaces, usually by raising a TabError. However, by default, mixing tabs and spaces is still allowed in Python 2, but it is highly recommended not to use this "feature". Use the -t and -tt command line flags to force Python 2 to raise a warning or (preferably) an error respectively. PEP8 also discusses this topic:
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!
What does "IndentationError: unexpected indent" mean?
Problem
This error occurs when a statement is unnecessarily indented or its indentation does not match the indentation of former statements in the same block. For example, the first statement in the program below is unnecessarily indented:
>>> print('Hello') # this is indented
File "<stdin>", line 1
print('Hello') # this is indented
^
IndentationError: unexpected indent
In this example, the can_drive = True line in the if block does not match the indentation of any former statement:
>>> age = 10
>>> can_drive = None
>>>
>>> if age >= 18:
... print('You can drive')
... can_drive = True # incorrectly indented
File "<stdin>", line 3
can_drive = True # incorrectly indented
^
IndentationError: unexpected indent
Fix
The fix for this error is to first make sure the problematic line even needs to be indented. For example, the above example using print can be fixed simply be unindenting the line:
>>> print('Hello') # simply unindent the line
Hello
However, if you are sure the line does need to be indented, the indentation needs to match that of a former statement in the same block. In the second example above using if, we can fix the error by making sure the line with can_drive = True is indented at the same level as the former statements in the if body:
>>> age = 10
>>> can_drive = None
>>>
>>> if age >= 18:
... print('You can drive')
... can_drive = True # indent this line at the same level.
...
What does "IndentationError: expected an indented block" mean?
(This might also occur as SyntaxError: unexpected EOF while parsing in Python 3.8 or lower.)
Problem
This error occurs when Python sees the 'header' for a compound statement, such as if <condition>: or while <condition>: but the compound statement's body or block is never defined. For example in the code below we began an if statement, but we never define a body for the statement:
>>> if True:
...
File "<stdin>", line 2
^
IndentationError: expected an indented block
In this second example, we began writing a for loop, but we forget to indent the for loop body. So Python still expects an indented block for the for loop body:
>>> names = ['sarah', 'lucy', 'michael']
>>> for name in names:
... print(name)
File "<stdin>", line 2
print(name)
^
IndentationError: expected an indented block
Comments don't count as bodies:
>>> if True:
... # TODO
...
File "<stdin>", line 3
^
IndentationError: expected an indented block
Fix
The fix for this error is to simply include a body for the compound statement.
As shown above, a common mistake by new users is that they forget to indent the body. If this is the case, make sure each statement meant to be included in the compound statement's body is indented at the same level under the compound statement's beginning. Here is the above example fixed:
>>> names = ['sarah', 'lucy', 'michael']
>>> for name in names:
... print(name) # The for loop body is now correctly indented.
...
sarah
lucy
michael
Another common case is that, for some reason, a user may not want to define an actual body for the compound statement, or the body may be commented out. In this case, the pass statement can be used. The pass statement can be used anywhere Python expects one or more statements as a placeholder. From the documentation for pass:
pass is a null operation — when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:
def f(arg): pass # a function that does nothing (yet)
class C: pass # a class with no methods (yet)
Here is the above example with the if statement fixed by using the pass keyword:
>>> if True:
... pass # We don't want to define a body.
...
>>>
What does "IndentationError: unindent does not match any outer indentation level" mean?
Problem
This error occurs when you unindent a statement, but now the indentation level of that statement does not match that of any former statement. For example, in the below code we unindent the second call to print. However, the indentation level does not match that of any former statement:
>>> if True:
... if True:
... print('yes')
... print()
File "<stdin>", line 4
print()
^
IndentationError: unindent does not match any outer indentation level
This error is especially hard to catch because even one space will cause your code to fail.
Fix
The fix is to ensure that when you unindent a statement, the indentation level matches that of a former statement. Consider the above example once again. In the example, I want the second call to print to be in the first if statements body. So I need to make sure that that line's indentation level matches that of the former statements in the first if statement's body:
>>> if True:
... if True:
... print('yes')
... print() # indentation level now matches former statement's level.
...
yes
>>>
I'm still getting an IndentationError but my program appears to be correctly indented. What do I do?
If your program visually appears to have correct indentation, but your still getting an IndentationError you have most likely mixed tabs with spaces. This will sometimes cause Python to raises strange errors. See the subsection Special cases under What does "TabError: inconsistent use of tabs and spaces in indentation" mean? for an more in-depth explanation of the problem.
What does "TabError: inconsistent use of tabs and spaces in indentation" mean?
Problem
This error only occurs when you attempt to mix tabs and spaces as indentation characters. As said above, Python will not allow your program to contain a mix of tabs and spaces, and will raise the specific exception TabError if it finds you have. For example, in the program below, a mix of tabs and spaces is used for indentation:
>>> if True:
... if True:
... print()
... print()
... print()
File "<stdin>", line 5
print()
^
TabError: inconsistent use of tabs and spaces in indentation
Here is a picture which visually shows the whitespace in the above program. Gray dots are spaces, and gray arrows are tabs:
We can see we have indeed mixed spaces and tabs for indentation.
Special cases
Note Python will not always raise a TabError if you mix tabs and spaces into your program. If the program indentation is unambiguous, Python will allow tabs and spaces to be mixed. For example:
>>> if True:
... if True: # tab
... pass # tab, then 4 spaces
...
>>>
And sometimes Python simply chokes on the mixture of tabs and spaces and erroneously raises an IndentationError exception when a TabError would be more appropriate. Another example:
>>> if True:
... pass # tab
... pass # 4 spaces
File "<stdin>", line 3
pass # 4 spaces
^
IndentationError: unindent does not match any outer indentation level
As you can see, running your code this way can create mysterious errors. Even though the program visually appears to be fine, Python became confused trying to parse the tabs and spaces used for indention and errored out.
These are excellent examples that demonstrate why to never mix tabs and spaces and make use of the -t and -tt interpreter flags when using Python 2.
Fix
If your program is short, probably the easiest and quickest fix is to simply re-indent the program. Make sure each statement is indented by four spaces per indention level (see How do I indent my code?).
However, if you already have a large program that you've mixed tabs and spaces into, there are automated tools that can be used to convert all of your indentation to just spaces.
Many editors such as PyCharm and SublimeText have options to automatically convert tabs to spaces. There are also several on-line tools such as Tabs To Spaces or Browserling that allow you to quickly re-indent your code. There are also tools written in Python. autopep8 for example can automatically re-indent your code and fix other indentation errors as well.
Even the best tools though will sometimes not be able to fix all of your indentation errors and you'll have to fix them manually. That's why it's important to always properly indent your code from the start.
A note about "SyntaxError" related indentation problems
Although not often, sometimes certain SyntaxError exceptions are raised due to incorrect indentation. For example, look at the code below:
if True:
pass
pass # oops! this statement should be indented!.
else:
pass
When the above code is run, a SyntaxError is raised:
Traceback (most recent call last):
File "python", line 4
else:
^
SyntaxError: invalid syntax
Although Python raises a SyntaxError, the real problem with the above code is that the second pass statement should be indented. Because the second pass isn't indented, Python doesn't realize that the previous if statement and the else statement are meant to be connected.
The fix for this type of error is to simply correctly re-indent your code. To see how to properly indent your code, see the section How do I indent my code?.
I'm still having a hard time with Python's indentation syntax. What do I do?
Don't get discouraged if you're still struggling. It can take time to get use to
Python's whitespace syntax rules. Here are some tips to help:
Get an editor that will tell you when you have an indentation error. Some goods ones are as said above are, PyCharm, SublimeText, and Jupyter Notebook.
When you indent your code, count out loud to yourself how many times you press the space-bar (or tab key). For example, if you needed to indent a line by four spaces, you would say out loud "one, two, three, four" while simultaneously pressing the space-bar each time. It sounds silly, but it helps train your brain to think about how deep you're indenting your code.
If you have an editor, see if it has an option to automatically convert tabs to spaces.
View others' code. Browse github or Stackoverflow and see examples of Python code.
Just write code. That's the single best way to get better. The more you write Python code, the better you'll get.
Resources used
https://en.wikipedia.org/
https://docs.python.org/3/
http://python-history.blogspot.com/2009/02/early-language-design-and-development.html
https://www.python.org/dev/peps/pep-0008/
Sublime Text 3
If it happens that you code in Sublime Text 3, this could help you with indentations problemes
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
}
You see, you have a tiny error.
if True:
if False:
print('foo')
print('bar')
You were supposed to do:
if True:
if False:
print('foo')
print('bar')
As you can see your print is only indented 3 spaces, it is supposed to be indented 4 spaces.
Historical note for Python 2
By default, Python 2 allowed tabs and spaces to be mixed, and would not produce an error by default. Passing the -tt option to Python 2.x causes it to raise an exception in the same cases that 3.x does, and -t causes a warning instead. The full details are explained at Python's interpretation of tabs and spaces to indent.
Note in particular that tabs are treated as 8 spaces (rather, they effectively increase the number of perceived spaces up to the next multiple of 8). Thus, if you were displaying the code with a standard 4-space indent, but have mixed spaces and tabs, you could end up with code that satisfies the indentation rules, but is not considered to be indented the same way that it looks.
As a result, you could get all kinds of other errors. For example:
# in 2.x
def example():
def nested(): # suppose this is indented with a tab
x = [1] # and this with two tabs
print x[0] + 1 # but this with 8 spaces instead of a tab
nested()
(Note that Stack Overflow's Markdown rendering will show the indentation as spaces even if I use tabs.)
That gives a NameError, since print x is no longer inside the nested function and x is out of scope in the outer example. Similarly, we could easily create a TypeError by giving example a local x = 1, or ValueError by giving it a local x = [].
Quick checklist
Incorrect indentation most commonly results in IndentationError, but it can also result in TabError (a sub-type of IndentationError) or SyntaxError (the indentation itself was legal, but it caused other code to have a syntax error). Indentation that is valid for Python code, but wrong for the programmer's intent, causes logical errors (the code doesn't raise an exception, but does something wrong).
It is strongly recommended not to use tabs for indentation. In 2.x, running Python with the -tt command line argument causes it to raise the same TabError, which is useful for finding problems.
The community standard, laid out in PEP 8, is to use four spaces per level of indentation.
Statements like if, for, def and class that end with a colon :, need an indented block after them:
if x:
do_y() # <- this must be indented
Blocks cannot be empty. Use the pass statement if nothing should happen:
if x:
pass # this statement does nothing, except make the block non-empty
Code within a block must have the same indentation:
if x:
do_y()
do_z() # this needs to line up with do_y()
The first line of code that lines up with the opening statement, or a lower level of indentation, is outside the block:
if x:
do_y()
do_z() # this happens regardless of the x value
# cannot write `else`: here; that is a syntax error
for i in range(10):
if x:
do_y()
do_z() # both the `if` and `for` blocks are ended
Python interprets tabs as expanding to the next 8th column; but in 3.x, indentation that mixes spaces and tabs must have the exact same pattern to count as the same indentation (and to indent further requires having the same pattern as a prefix). Failure to get this right results in TabError.
while and for loops in Python may have an else clause, which executes if the loop complete normally rather than via break. This is a common source of logical errors:
for i in range(10):
if i % 2:
print(f'{i} is odd')
else: # wrongly indented
print(f'{i} is even') # only happens once, and claims 9 is even!
Quick fix for Sublime users:
Press Ctrl-H to access Find and Replace
In Find: Type 4 spaces
In Replace: Copy and paste a tab from somewhere in your code
Click Replace All

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.

Indentation error: unindent doesnot match outer loop (in an if else statement ) [duplicate]

I have a Python script:
if True:
if False:
print('foo')
print('bar')
However, when I attempt to run my script, Python raises an IndentationError:
File "script.py", line 4
print('bar')
^
IndentationError: unindent does not match any outer indentation level
I kept playing around with my program, and I was able to produce four errors in total:
IndentationError: unexpected indent
IndentationError: expected an indented block
TabError: inconsistent use of tabs and spaces in indentation
IndentationError: unindent does not match any outer indentation level
What do these errors mean? What am I doing wrong? How can I fix my code?
Note: This is an attempt at a canonical question because I see many similar posts every month. This is not a duplicate of existing questions about unindents or unexpected indents because they only deal with one type of indentation error each, and I'm looking to cover them all in one place.
It's also possible to have logically incorrect indentation that does not cause an error message. One common form of this is attaching else: to a for or while loop rather than (as intended) the corresponding if:. See Else clause on Python while statement if you need to close questions where OP did that.
Why does indentation matter?
In Python, indentation is used to delimit blocks of code. This is different from many other languages that use curly braces {} to delimit blocks such as Java, Javascript, and C. Because of this, Python users must pay close attention to when and how they indent their code because whitespace matters.
When Python encounters a problem with the indentation of your program, it either raises an exception called IndentationError or TabError.
A little history
The historical reasons for why Python uses indentation vs the arguably more commonly accepted curly braces {} is outlined in an article of the history of Python by Guido van Rossum - the creator of Python:
Python’s use of indentation comes directly from ABC, but this idea didn’t originate with ABC--it had already been promoted by Donald Knuth and was a well-known concept of programming style. (The occam programming language also used it.) However, ABC’s authors did invent the use of the colon that separates the lead-in clause from the indented block. After early user testing without the colon, it was discovered that the meaning of the indentation was unclear to beginners being taught the first steps of programming. The addition of the colon clarified it significantly: the colon somehow draws attention to what follows and ties the phrases before and after it together in just the right way.
How do I indent my code?
The basic rule for indenting Python code (considering that you treat the entire program as a "basic block") is: The first statement in a basic block, and each subsequent statement after it must be indented by the same amount.
So technically the following Python program is correct:
def perm(l):
# Compute the list of all permutations of l
if len(l) <= 1:
return [l]
r = []
for i in range(len(l)):
s = l[:i] + l[i+1:]
p = perm(s)
for x in p:
r.append(l[i:i+1] + x)
return r
However, as you can probably tell from above, randomly indenting your code makes is extremely hard to read and follow the flow of the program. It's better to be consistent and follow a style.
PEP 8 -- the Python style guide -- says:
Use 4 spaces per indentation level.
That is, each statement that is starting a new block and each subsequent statement in the new block, should be indented four spaces from the current indentation level. Here is the above program indented according to the PEP8 style guide:
def perm(l):
# Compute the list of all permutations of l
if len(l) <= 1:
return [l]
r = []
for i in range(len(l)):
s = l[:i] + l[i+1:]
p = perm(s)
for x in p:
r.append(l[i:i+1] + x)
return r
Can I still use tabs?
Python realizes that some people still prefer tabs over spaces and that legacy code may use tabs rather than spaces, so it allows the use of tabs as indentation. PEP8 touches on this topic:
Spaces are the preferred indentation method.
Tabs should be used solely to remain consistent with code that is already indented with tabs.
Note however the one big caveat is not to use both tabs and spaces for indentation. Doing so can cause all kinds of strange hard to debug indentation errors. Python expands tabs to the next 8th column, but if your editor is set to a tab size of 4 columns, or you you use spaces as well as tabs, you can easily produce indented code that looks fine in your editor, but Python will refuse to run. The Python 3 compiler explicitly rejects any program containing an ambiguous mixture of tabs and spaces, usually by raising a TabError. However, by default, mixing tabs and spaces is still allowed in Python 2, but it is highly recommended not to use this "feature". Use the -t and -tt command line flags to force Python 2 to raise a warning or (preferably) an error respectively. PEP8 also discusses this topic:
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!
What does "IndentationError: unexpected indent" mean?
Problem
This error occurs when a statement is unnecessarily indented or its indentation does not match the indentation of former statements in the same block. For example, the first statement in the program below is unnecessarily indented:
>>> print('Hello') # this is indented
File "<stdin>", line 1
print('Hello') # this is indented
^
IndentationError: unexpected indent
In this example, the can_drive = True line in the if block does not match the indentation of any former statement:
>>> age = 10
>>> can_drive = None
>>>
>>> if age >= 18:
... print('You can drive')
... can_drive = True # incorrectly indented
File "<stdin>", line 3
can_drive = True # incorrectly indented
^
IndentationError: unexpected indent
Fix
The fix for this error is to first make sure the problematic line even needs to be indented. For example, the above example using print can be fixed simply be unindenting the line:
>>> print('Hello') # simply unindent the line
Hello
However, if you are sure the line does need to be indented, the indentation needs to match that of a former statement in the same block. In the second example above using if, we can fix the error by making sure the line with can_drive = True is indented at the same level as the former statements in the if body:
>>> age = 10
>>> can_drive = None
>>>
>>> if age >= 18:
... print('You can drive')
... can_drive = True # indent this line at the same level.
...
What does "IndentationError: expected an indented block" mean?
(This might also occur as SyntaxError: unexpected EOF while parsing in Python 3.8 or lower.)
Problem
This error occurs when Python sees the 'header' for a compound statement, such as if <condition>: or while <condition>: but the compound statement's body or block is never defined. For example in the code below we began an if statement, but we never define a body for the statement:
>>> if True:
...
File "<stdin>", line 2
^
IndentationError: expected an indented block
In this second example, we began writing a for loop, but we forget to indent the for loop body. So Python still expects an indented block for the for loop body:
>>> names = ['sarah', 'lucy', 'michael']
>>> for name in names:
... print(name)
File "<stdin>", line 2
print(name)
^
IndentationError: expected an indented block
Comments don't count as bodies:
>>> if True:
... # TODO
...
File "<stdin>", line 3
^
IndentationError: expected an indented block
Fix
The fix for this error is to simply include a body for the compound statement.
As shown above, a common mistake by new users is that they forget to indent the body. If this is the case, make sure each statement meant to be included in the compound statement's body is indented at the same level under the compound statement's beginning. Here is the above example fixed:
>>> names = ['sarah', 'lucy', 'michael']
>>> for name in names:
... print(name) # The for loop body is now correctly indented.
...
sarah
lucy
michael
Another common case is that, for some reason, a user may not want to define an actual body for the compound statement, or the body may be commented out. In this case, the pass statement can be used. The pass statement can be used anywhere Python expects one or more statements as a placeholder. From the documentation for pass:
pass is a null operation — when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:
def f(arg): pass # a function that does nothing (yet)
class C: pass # a class with no methods (yet)
Here is the above example with the if statement fixed by using the pass keyword:
>>> if True:
... pass # We don't want to define a body.
...
>>>
What does "IndentationError: unindent does not match any outer indentation level" mean?
Problem
This error occurs when you unindent a statement, but now the indentation level of that statement does not match that of any former statement. For example, in the below code we unindent the second call to print. However, the indentation level does not match that of any former statement:
>>> if True:
... if True:
... print('yes')
... print()
File "<stdin>", line 4
print()
^
IndentationError: unindent does not match any outer indentation level
This error is especially hard to catch because even one space will cause your code to fail.
Fix
The fix is to ensure that when you unindent a statement, the indentation level matches that of a former statement. Consider the above example once again. In the example, I want the second call to print to be in the first if statements body. So I need to make sure that that line's indentation level matches that of the former statements in the first if statement's body:
>>> if True:
... if True:
... print('yes')
... print() # indentation level now matches former statement's level.
...
yes
>>>
I'm still getting an IndentationError but my program appears to be correctly indented. What do I do?
If your program visually appears to have correct indentation, but your still getting an IndentationError you have most likely mixed tabs with spaces. This will sometimes cause Python to raises strange errors. See the subsection Special cases under What does "TabError: inconsistent use of tabs and spaces in indentation" mean? for an more in-depth explanation of the problem.
What does "TabError: inconsistent use of tabs and spaces in indentation" mean?
Problem
This error only occurs when you attempt to mix tabs and spaces as indentation characters. As said above, Python will not allow your program to contain a mix of tabs and spaces, and will raise the specific exception TabError if it finds you have. For example, in the program below, a mix of tabs and spaces is used for indentation:
>>> if True:
... if True:
... print()
... print()
... print()
File "<stdin>", line 5
print()
^
TabError: inconsistent use of tabs and spaces in indentation
Here is a picture which visually shows the whitespace in the above program. Gray dots are spaces, and gray arrows are tabs:
We can see we have indeed mixed spaces and tabs for indentation.
Special cases
Note Python will not always raise a TabError if you mix tabs and spaces into your program. If the program indentation is unambiguous, Python will allow tabs and spaces to be mixed. For example:
>>> if True:
... if True: # tab
... pass # tab, then 4 spaces
...
>>>
And sometimes Python simply chokes on the mixture of tabs and spaces and erroneously raises an IndentationError exception when a TabError would be more appropriate. Another example:
>>> if True:
... pass # tab
... pass # 4 spaces
File "<stdin>", line 3
pass # 4 spaces
^
IndentationError: unindent does not match any outer indentation level
As you can see, running your code this way can create mysterious errors. Even though the program visually appears to be fine, Python became confused trying to parse the tabs and spaces used for indention and errored out.
These are excellent examples that demonstrate why to never mix tabs and spaces and make use of the -t and -tt interpreter flags when using Python 2.
Fix
If your program is short, probably the easiest and quickest fix is to simply re-indent the program. Make sure each statement is indented by four spaces per indention level (see How do I indent my code?).
However, if you already have a large program that you've mixed tabs and spaces into, there are automated tools that can be used to convert all of your indentation to just spaces.
Many editors such as PyCharm and SublimeText have options to automatically convert tabs to spaces. There are also several on-line tools such as Tabs To Spaces or Browserling that allow you to quickly re-indent your code. There are also tools written in Python. autopep8 for example can automatically re-indent your code and fix other indentation errors as well.
Even the best tools though will sometimes not be able to fix all of your indentation errors and you'll have to fix them manually. That's why it's important to always properly indent your code from the start.
A note about "SyntaxError" related indentation problems
Although not often, sometimes certain SyntaxError exceptions are raised due to incorrect indentation. For example, look at the code below:
if True:
pass
pass # oops! this statement should be indented!.
else:
pass
When the above code is run, a SyntaxError is raised:
Traceback (most recent call last):
File "python", line 4
else:
^
SyntaxError: invalid syntax
Although Python raises a SyntaxError, the real problem with the above code is that the second pass statement should be indented. Because the second pass isn't indented, Python doesn't realize that the previous if statement and the else statement are meant to be connected.
The fix for this type of error is to simply correctly re-indent your code. To see how to properly indent your code, see the section How do I indent my code?.
I'm still having a hard time with Python's indentation syntax. What do I do?
Don't get discouraged if you're still struggling. It can take time to get use to
Python's whitespace syntax rules. Here are some tips to help:
Get an editor that will tell you when you have an indentation error. Some goods ones are as said above are, PyCharm, SublimeText, and Jupyter Notebook.
When you indent your code, count out loud to yourself how many times you press the space-bar (or tab key). For example, if you needed to indent a line by four spaces, you would say out loud "one, two, three, four" while simultaneously pressing the space-bar each time. It sounds silly, but it helps train your brain to think about how deep you're indenting your code.
If you have an editor, see if it has an option to automatically convert tabs to spaces.
View others' code. Browse github or Stackoverflow and see examples of Python code.
Just write code. That's the single best way to get better. The more you write Python code, the better you'll get.
Resources used
https://en.wikipedia.org/
https://docs.python.org/3/
http://python-history.blogspot.com/2009/02/early-language-design-and-development.html
https://www.python.org/dev/peps/pep-0008/
Sublime Text 3
If it happens that you code in Sublime Text 3, this could help you with indentations problemes
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
}
You see, you have a tiny error.
if True:
if False:
print('foo')
print('bar')
You were supposed to do:
if True:
if False:
print('foo')
print('bar')
As you can see your print is only indented 3 spaces, it is supposed to be indented 4 spaces.
Historical note for Python 2
By default, Python 2 allowed tabs and spaces to be mixed, and would not produce an error by default. Passing the -tt option to Python 2.x causes it to raise an exception in the same cases that 3.x does, and -t causes a warning instead. The full details are explained at Python's interpretation of tabs and spaces to indent.
Note in particular that tabs are treated as 8 spaces (rather, they effectively increase the number of perceived spaces up to the next multiple of 8). Thus, if you were displaying the code with a standard 4-space indent, but have mixed spaces and tabs, you could end up with code that satisfies the indentation rules, but is not considered to be indented the same way that it looks.
As a result, you could get all kinds of other errors. For example:
# in 2.x
def example():
def nested(): # suppose this is indented with a tab
x = [1] # and this with two tabs
print x[0] + 1 # but this with 8 spaces instead of a tab
nested()
(Note that Stack Overflow's Markdown rendering will show the indentation as spaces even if I use tabs.)
That gives a NameError, since print x is no longer inside the nested function and x is out of scope in the outer example. Similarly, we could easily create a TypeError by giving example a local x = 1, or ValueError by giving it a local x = [].
Quick checklist
Incorrect indentation most commonly results in IndentationError, but it can also result in TabError (a sub-type of IndentationError) or SyntaxError (the indentation itself was legal, but it caused other code to have a syntax error). Indentation that is valid for Python code, but wrong for the programmer's intent, causes logical errors (the code doesn't raise an exception, but does something wrong).
It is strongly recommended not to use tabs for indentation. In 2.x, running Python with the -tt command line argument causes it to raise the same TabError, which is useful for finding problems.
The community standard, laid out in PEP 8, is to use four spaces per level of indentation.
Statements like if, for, def and class that end with a colon :, need an indented block after them:
if x:
do_y() # <- this must be indented
Blocks cannot be empty. Use the pass statement if nothing should happen:
if x:
pass # this statement does nothing, except make the block non-empty
Code within a block must have the same indentation:
if x:
do_y()
do_z() # this needs to line up with do_y()
The first line of code that lines up with the opening statement, or a lower level of indentation, is outside the block:
if x:
do_y()
do_z() # this happens regardless of the x value
# cannot write `else`: here; that is a syntax error
for i in range(10):
if x:
do_y()
do_z() # both the `if` and `for` blocks are ended
Python interprets tabs as expanding to the next 8th column; but in 3.x, indentation that mixes spaces and tabs must have the exact same pattern to count as the same indentation (and to indent further requires having the same pattern as a prefix). Failure to get this right results in TabError.
while and for loops in Python may have an else clause, which executes if the loop complete normally rather than via break. This is a common source of logical errors:
for i in range(10):
if i % 2:
print(f'{i} is odd')
else: # wrongly indented
print(f'{i} is even') # only happens once, and claims 9 is even!
Quick fix for Sublime users:
Press Ctrl-H to access Find and Replace
In Find: Type 4 spaces
In Replace: Copy and paste a tab from somewhere in your code
Click Replace All

"def listening(self,phrases=None):" Eror in python [duplicate]

I have a Python script:
if True:
if False:
print('foo')
print('bar')
However, when I attempt to run my script, Python raises an IndentationError:
File "script.py", line 4
print('bar')
^
IndentationError: unindent does not match any outer indentation level
I kept playing around with my program, and I was able to produce four errors in total:
IndentationError: unexpected indent
IndentationError: expected an indented block
TabError: inconsistent use of tabs and spaces in indentation
IndentationError: unindent does not match any outer indentation level
What do these errors mean? What am I doing wrong? How can I fix my code?
Note: This is an attempt at a canonical question because I see many similar posts every month. This is not a duplicate of existing questions about unindents or unexpected indents because they only deal with one type of indentation error each, and I'm looking to cover them all in one place.
It's also possible to have logically incorrect indentation that does not cause an error message. One common form of this is attaching else: to a for or while loop rather than (as intended) the corresponding if:. See Else clause on Python while statement if you need to close questions where OP did that.
Why does indentation matter?
In Python, indentation is used to delimit blocks of code. This is different from many other languages that use curly braces {} to delimit blocks such as Java, Javascript, and C. Because of this, Python users must pay close attention to when and how they indent their code because whitespace matters.
When Python encounters a problem with the indentation of your program, it either raises an exception called IndentationError or TabError.
A little history
The historical reasons for why Python uses indentation vs the arguably more commonly accepted curly braces {} is outlined in an article of the history of Python by Guido van Rossum - the creator of Python:
Python’s use of indentation comes directly from ABC, but this idea didn’t originate with ABC--it had already been promoted by Donald Knuth and was a well-known concept of programming style. (The occam programming language also used it.) However, ABC’s authors did invent the use of the colon that separates the lead-in clause from the indented block. After early user testing without the colon, it was discovered that the meaning of the indentation was unclear to beginners being taught the first steps of programming. The addition of the colon clarified it significantly: the colon somehow draws attention to what follows and ties the phrases before and after it together in just the right way.
How do I indent my code?
The basic rule for indenting Python code (considering that you treat the entire program as a "basic block") is: The first statement in a basic block, and each subsequent statement after it must be indented by the same amount.
So technically the following Python program is correct:
def perm(l):
# Compute the list of all permutations of l
if len(l) <= 1:
return [l]
r = []
for i in range(len(l)):
s = l[:i] + l[i+1:]
p = perm(s)
for x in p:
r.append(l[i:i+1] + x)
return r
However, as you can probably tell from above, randomly indenting your code makes is extremely hard to read and follow the flow of the program. It's better to be consistent and follow a style.
PEP 8 -- the Python style guide -- says:
Use 4 spaces per indentation level.
That is, each statement that is starting a new block and each subsequent statement in the new block, should be indented four spaces from the current indentation level. Here is the above program indented according to the PEP8 style guide:
def perm(l):
# Compute the list of all permutations of l
if len(l) <= 1:
return [l]
r = []
for i in range(len(l)):
s = l[:i] + l[i+1:]
p = perm(s)
for x in p:
r.append(l[i:i+1] + x)
return r
Can I still use tabs?
Python realizes that some people still prefer tabs over spaces and that legacy code may use tabs rather than spaces, so it allows the use of tabs as indentation. PEP8 touches on this topic:
Spaces are the preferred indentation method.
Tabs should be used solely to remain consistent with code that is already indented with tabs.
Note however the one big caveat is not to use both tabs and spaces for indentation. Doing so can cause all kinds of strange hard to debug indentation errors. Python expands tabs to the next 8th column, but if your editor is set to a tab size of 4 columns, or you you use spaces as well as tabs, you can easily produce indented code that looks fine in your editor, but Python will refuse to run. The Python 3 compiler explicitly rejects any program containing an ambiguous mixture of tabs and spaces, usually by raising a TabError. However, by default, mixing tabs and spaces is still allowed in Python 2, but it is highly recommended not to use this "feature". Use the -t and -tt command line flags to force Python 2 to raise a warning or (preferably) an error respectively. PEP8 also discusses this topic:
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!
What does "IndentationError: unexpected indent" mean?
Problem
This error occurs when a statement is unnecessarily indented or its indentation does not match the indentation of former statements in the same block. For example, the first statement in the program below is unnecessarily indented:
>>> print('Hello') # this is indented
File "<stdin>", line 1
print('Hello') # this is indented
^
IndentationError: unexpected indent
In this example, the can_drive = True line in the if block does not match the indentation of any former statement:
>>> age = 10
>>> can_drive = None
>>>
>>> if age >= 18:
... print('You can drive')
... can_drive = True # incorrectly indented
File "<stdin>", line 3
can_drive = True # incorrectly indented
^
IndentationError: unexpected indent
Fix
The fix for this error is to first make sure the problematic line even needs to be indented. For example, the above example using print can be fixed simply be unindenting the line:
>>> print('Hello') # simply unindent the line
Hello
However, if you are sure the line does need to be indented, the indentation needs to match that of a former statement in the same block. In the second example above using if, we can fix the error by making sure the line with can_drive = True is indented at the same level as the former statements in the if body:
>>> age = 10
>>> can_drive = None
>>>
>>> if age >= 18:
... print('You can drive')
... can_drive = True # indent this line at the same level.
...
What does "IndentationError: expected an indented block" mean?
(This might also occur as SyntaxError: unexpected EOF while parsing in Python 3.8 or lower.)
Problem
This error occurs when Python sees the 'header' for a compound statement, such as if <condition>: or while <condition>: but the compound statement's body or block is never defined. For example in the code below we began an if statement, but we never define a body for the statement:
>>> if True:
...
File "<stdin>", line 2
^
IndentationError: expected an indented block
In this second example, we began writing a for loop, but we forget to indent the for loop body. So Python still expects an indented block for the for loop body:
>>> names = ['sarah', 'lucy', 'michael']
>>> for name in names:
... print(name)
File "<stdin>", line 2
print(name)
^
IndentationError: expected an indented block
Comments don't count as bodies:
>>> if True:
... # TODO
...
File "<stdin>", line 3
^
IndentationError: expected an indented block
Fix
The fix for this error is to simply include a body for the compound statement.
As shown above, a common mistake by new users is that they forget to indent the body. If this is the case, make sure each statement meant to be included in the compound statement's body is indented at the same level under the compound statement's beginning. Here is the above example fixed:
>>> names = ['sarah', 'lucy', 'michael']
>>> for name in names:
... print(name) # The for loop body is now correctly indented.
...
sarah
lucy
michael
Another common case is that, for some reason, a user may not want to define an actual body for the compound statement, or the body may be commented out. In this case, the pass statement can be used. The pass statement can be used anywhere Python expects one or more statements as a placeholder. From the documentation for pass:
pass is a null operation — when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:
def f(arg): pass # a function that does nothing (yet)
class C: pass # a class with no methods (yet)
Here is the above example with the if statement fixed by using the pass keyword:
>>> if True:
... pass # We don't want to define a body.
...
>>>
What does "IndentationError: unindent does not match any outer indentation level" mean?
Problem
This error occurs when you unindent a statement, but now the indentation level of that statement does not match that of any former statement. For example, in the below code we unindent the second call to print. However, the indentation level does not match that of any former statement:
>>> if True:
... if True:
... print('yes')
... print()
File "<stdin>", line 4
print()
^
IndentationError: unindent does not match any outer indentation level
This error is especially hard to catch because even one space will cause your code to fail.
Fix
The fix is to ensure that when you unindent a statement, the indentation level matches that of a former statement. Consider the above example once again. In the example, I want the second call to print to be in the first if statements body. So I need to make sure that that line's indentation level matches that of the former statements in the first if statement's body:
>>> if True:
... if True:
... print('yes')
... print() # indentation level now matches former statement's level.
...
yes
>>>
I'm still getting an IndentationError but my program appears to be correctly indented. What do I do?
If your program visually appears to have correct indentation, but your still getting an IndentationError you have most likely mixed tabs with spaces. This will sometimes cause Python to raises strange errors. See the subsection Special cases under What does "TabError: inconsistent use of tabs and spaces in indentation" mean? for an more in-depth explanation of the problem.
What does "TabError: inconsistent use of tabs and spaces in indentation" mean?
Problem
This error only occurs when you attempt to mix tabs and spaces as indentation characters. As said above, Python will not allow your program to contain a mix of tabs and spaces, and will raise the specific exception TabError if it finds you have. For example, in the program below, a mix of tabs and spaces is used for indentation:
>>> if True:
... if True:
... print()
... print()
... print()
File "<stdin>", line 5
print()
^
TabError: inconsistent use of tabs and spaces in indentation
Here is a picture which visually shows the whitespace in the above program. Gray dots are spaces, and gray arrows are tabs:
We can see we have indeed mixed spaces and tabs for indentation.
Special cases
Note Python will not always raise a TabError if you mix tabs and spaces into your program. If the program indentation is unambiguous, Python will allow tabs and spaces to be mixed. For example:
>>> if True:
... if True: # tab
... pass # tab, then 4 spaces
...
>>>
And sometimes Python simply chokes on the mixture of tabs and spaces and erroneously raises an IndentationError exception when a TabError would be more appropriate. Another example:
>>> if True:
... pass # tab
... pass # 4 spaces
File "<stdin>", line 3
pass # 4 spaces
^
IndentationError: unindent does not match any outer indentation level
As you can see, running your code this way can create mysterious errors. Even though the program visually appears to be fine, Python became confused trying to parse the tabs and spaces used for indention and errored out.
These are excellent examples that demonstrate why to never mix tabs and spaces and make use of the -t and -tt interpreter flags when using Python 2.
Fix
If your program is short, probably the easiest and quickest fix is to simply re-indent the program. Make sure each statement is indented by four spaces per indention level (see How do I indent my code?).
However, if you already have a large program that you've mixed tabs and spaces into, there are automated tools that can be used to convert all of your indentation to just spaces.
Many editors such as PyCharm and SublimeText have options to automatically convert tabs to spaces. There are also several on-line tools such as Tabs To Spaces or Browserling that allow you to quickly re-indent your code. There are also tools written in Python. autopep8 for example can automatically re-indent your code and fix other indentation errors as well.
Even the best tools though will sometimes not be able to fix all of your indentation errors and you'll have to fix them manually. That's why it's important to always properly indent your code from the start.
A note about "SyntaxError" related indentation problems
Although not often, sometimes certain SyntaxError exceptions are raised due to incorrect indentation. For example, look at the code below:
if True:
pass
pass # oops! this statement should be indented!.
else:
pass
When the above code is run, a SyntaxError is raised:
Traceback (most recent call last):
File "python", line 4
else:
^
SyntaxError: invalid syntax
Although Python raises a SyntaxError, the real problem with the above code is that the second pass statement should be indented. Because the second pass isn't indented, Python doesn't realize that the previous if statement and the else statement are meant to be connected.
The fix for this type of error is to simply correctly re-indent your code. To see how to properly indent your code, see the section How do I indent my code?.
I'm still having a hard time with Python's indentation syntax. What do I do?
Don't get discouraged if you're still struggling. It can take time to get use to
Python's whitespace syntax rules. Here are some tips to help:
Get an editor that will tell you when you have an indentation error. Some goods ones are as said above are, PyCharm, SublimeText, and Jupyter Notebook.
When you indent your code, count out loud to yourself how many times you press the space-bar (or tab key). For example, if you needed to indent a line by four spaces, you would say out loud "one, two, three, four" while simultaneously pressing the space-bar each time. It sounds silly, but it helps train your brain to think about how deep you're indenting your code.
If you have an editor, see if it has an option to automatically convert tabs to spaces.
View others' code. Browse github or Stackoverflow and see examples of Python code.
Just write code. That's the single best way to get better. The more you write Python code, the better you'll get.
Resources used
https://en.wikipedia.org/
https://docs.python.org/3/
http://python-history.blogspot.com/2009/02/early-language-design-and-development.html
https://www.python.org/dev/peps/pep-0008/
Sublime Text 3
If it happens that you code in Sublime Text 3, this could help you with indentations problemes
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
}
You see, you have a tiny error.
if True:
if False:
print('foo')
print('bar')
You were supposed to do:
if True:
if False:
print('foo')
print('bar')
As you can see your print is only indented 3 spaces, it is supposed to be indented 4 spaces.
Historical note for Python 2
By default, Python 2 allowed tabs and spaces to be mixed, and would not produce an error by default. Passing the -tt option to Python 2.x causes it to raise an exception in the same cases that 3.x does, and -t causes a warning instead. The full details are explained at Python's interpretation of tabs and spaces to indent.
Note in particular that tabs are treated as 8 spaces (rather, they effectively increase the number of perceived spaces up to the next multiple of 8). Thus, if you were displaying the code with a standard 4-space indent, but have mixed spaces and tabs, you could end up with code that satisfies the indentation rules, but is not considered to be indented the same way that it looks.
As a result, you could get all kinds of other errors. For example:
# in 2.x
def example():
def nested(): # suppose this is indented with a tab
x = [1] # and this with two tabs
print x[0] + 1 # but this with 8 spaces instead of a tab
nested()
(Note that Stack Overflow's Markdown rendering will show the indentation as spaces even if I use tabs.)
That gives a NameError, since print x is no longer inside the nested function and x is out of scope in the outer example. Similarly, we could easily create a TypeError by giving example a local x = 1, or ValueError by giving it a local x = [].
Quick checklist
Incorrect indentation most commonly results in IndentationError, but it can also result in TabError (a sub-type of IndentationError) or SyntaxError (the indentation itself was legal, but it caused other code to have a syntax error). Indentation that is valid for Python code, but wrong for the programmer's intent, causes logical errors (the code doesn't raise an exception, but does something wrong).
It is strongly recommended not to use tabs for indentation. In 2.x, running Python with the -tt command line argument causes it to raise the same TabError, which is useful for finding problems.
The community standard, laid out in PEP 8, is to use four spaces per level of indentation.
Statements like if, for, def and class that end with a colon :, need an indented block after them:
if x:
do_y() # <- this must be indented
Blocks cannot be empty. Use the pass statement if nothing should happen:
if x:
pass # this statement does nothing, except make the block non-empty
Code within a block must have the same indentation:
if x:
do_y()
do_z() # this needs to line up with do_y()
The first line of code that lines up with the opening statement, or a lower level of indentation, is outside the block:
if x:
do_y()
do_z() # this happens regardless of the x value
# cannot write `else`: here; that is a syntax error
for i in range(10):
if x:
do_y()
do_z() # both the `if` and `for` blocks are ended
Python interprets tabs as expanding to the next 8th column; but in 3.x, indentation that mixes spaces and tabs must have the exact same pattern to count as the same indentation (and to indent further requires having the same pattern as a prefix). Failure to get this right results in TabError.
while and for loops in Python may have an else clause, which executes if the loop complete normally rather than via break. This is a common source of logical errors:
for i in range(10):
if i % 2:
print(f'{i} is odd')
else: # wrongly indented
print(f'{i} is even') # only happens once, and claims 9 is even!
Quick fix for Sublime users:
Press Ctrl-H to access Find and Replace
In Find: Type 4 spaces
In Replace: Copy and paste a tab from somewhere in your code
Click Replace All

Why am I getting "IndentationError: expected an indented block"? [duplicate]

This question already has answers here:
I'm getting an IndentationError. How do I fix it?
(6 answers)
Closed 26 days ago.
if len(trashed_files) == 0 :
print "No files trashed from current dir ('%s')" % os.path.realpath(os.curdir)
else :
index=raw_input("What file to restore [0..%d]: " % (len(trashed_files)-1))
if index == "*" :
for tfile in trashed_files :
try:
tfile.restore()
except IOError, e:
import sys
print >> sys.stderr, str(e)
sys.exit(1)
elif index == "" :
print "Exiting"
else :
index = int(index)
try:
trashed_files[index].restore()
except IOError, e:
import sys
print >> sys.stderr, str(e)
sys.exit(1)
I am getting:
elif index == "" :
^
IndentationError: expected an indented block
As the error message indicates, you have an indentation error. It is probably caused by a mix of tabs and spaces.
There are in fact multiples things you need to know about indentation in Python:
Python really cares about indention.
In a lot of other languages the indention is not necessary but improves readability. In Python indentation replaces the keyword begin / end or { } and is therefore necessary.
This is verified before the execution of the code, therefore even if the code with the indentation error is never reached, it won't work.
There are different indention errors and you reading them helps a lot:
1. "IndentationError: expected an indented block"
They are two main reasons why you could have such an error:
- You have a ":" without an indented block behind.
Here are two examples:
Example 1, no indented block:
Input:
if 3 != 4:
print("usual")
else:
Output:
File "<stdin>", line 4
^
IndentationError: expected an indented block
The output states that you need to have an indented block on line 4, after the else: statement
Example 2, unindented block:
Input:
if 3 != 4:
print("usual")
Output
File "<stdin>", line 2
print("usual")
^
IndentationError: expected an indented block
The output states that you need to have an indented block line 2, after the if 3 != 4: statement
- You are using Python2.x and have a mix of tabs and spaces:
Input
def foo():
if 1:
print 1
Please note that before if, there is a tab, and before print there is 8 spaces.
Output:
File "<stdin>", line 3
print 1
^
IndentationError: expected an indented block
It's quite hard to understand what is happening here, it seems that there is an indent block... But as I said, I've used tabs and spaces, and you should never do that.
You can get some info here.
Remove all tabs and replaces them by four spaces.
And configure your editor to do that automatically.
2. "IndentationError: unexpected indent"
It is important to indent blocks, but only blocks that should be indent.
So basically this error says:
- You have an indented block without a ":" before it.
Example:
Input:
a = 3
a += 3
Output:
File "<stdin>", line 2
a += 3
^
IndentationError: unexpected indent
The output states that he wasn't expecting an indent block line 2, then you should remove it.
3. "TabError: inconsistent use of tabs and spaces in indentation" (python3.x only)
You can get some info here.
But basically it's, you are using tabs and spaces in your code.
You don't want that.
Remove all tabs and replaces them by four spaces.
And configure your editor to do that automatically.
Eventually, to come back on your problem:
Just look at the line number of the error, and fix it using the previous information.
I had this same problem and discovered (via this answer to a similar question) that the problem was that I didn't properly indent the docstring properly. Unfortunately IDLE doesn't give useful feedback here, but once I fixed the docstring indentation, the problem went away.
Specifically --- bad code that generates indentation errors:
def my_function(args):
"Here is my docstring"
....
Good code that avoids indentation errors:
def my_function(args):
"Here is my docstring"
....
Note: I'm not saying this is the problem, but that it might be, because in my case, it was!
You might want to check you spaces and tabs. A tab is a default of 4 spaces. However, your "if" and "elif" match, so I am not quite sure why. Go into Options in the top bar, and click "Configure IDLE". Check the Indentation Width on the right in Fonts/Tabs, and make sure your indents have that many spaces.
in python intended block mean there is every thing must be written in manner in my case I written it this way
def btnClick(numbers):
global operator
operator = operator + str(numbers)
text_input.set(operator)
Note.its give me error,until I written it in this way such that "giving spaces " then its giving me a block as I am trying to show you in function below code
def btnClick(numbers):
___________________________
|global operator
|operator = operator + str(numbers)
|text_input.set(operator)
This is just an indentation problem since Python is very strict when it comes to it.
If you are using Sublime, you can select all, click on the lower right beside 'Python' and make sure you check 'Indent using spaces' and choose your Tab Width to be consistent, then Convert Indentation to Spaces to convert all tabs to spaces.

Categories