Python indentation is a part of the syntax. It’s not just for decoration.
You’ll learn what these errors mean and how to solve them:
- IndentationError: unexpected indent
- IndentationError: expected an indented block
- IndentationError: unindent does not match any outer indentation level
- IndentationError: unexpected unindent
So if you want to learn how to solve those errors, then you’re in the right place.
Let’s kick things off with error #1!
- How to Solve ImportError: Attempted Relative Import With No Known Parent Package (Python)
- SyntaxError: Invalid Character in Identifier: How to Solve? (Python)
- How to Solve ‘Tuple’ Object Does Not Support Item Assignment (Python)
- 3 Ways to Solve Series Objects Are Mutable and Cannot be Hashed (Python)
- 9 Examples of Unexpected Character After Line Continuation Character (Python)
How to Solve IndentationError: unexpected indent in Python
Python is a beautiful language. One of the key features of this beauty is the lack of curly braces and other symbols that mark the beginning and end of each block.
Even in C it is considered a good practice to indent, denoting different levels in the code. Compare the same C ++ code with and without indentation. First with the indentation:
#include <iostream>
#include <windows.h>
#include<time.h>
using namespace std;
void main()
{
srand (unsigned (time(NULL)));
int a,b,i;
cout<<"Guess number game".\n\n";
a=rand()%10+1;
cout<<"AI conceived a number from 1 to 10.\n";
cout<<"Enter your guess and press <Enter>\n\n";
for(i=1;i<3;i++)
{
cout<<"--->";
cin>>b;
if(b==a)
{
cout<<"You won! Congrats!\n";
cout<<"You guessed with "<<i<<" try!\n";
break;
}
if(b!=a)
{
cout<<"No, that's the other number. Try again!\n";
}
}
if(b!=a&&i==3)
{
cout<<"You lose!\n";
}
}
And the same code without indentation:
#include <iostream>
#include <windows.h>
#include<time.h>
using namespace std;
void main()
{
srand (unsigned (time(NULL)));
int a,b,i;
cout<<"Guess number game\n";
a=rand()%10+1;
cout<<"AI conceived a number from 1 to 10\n";
cout<<"Enter your guess and press <Enter>\n";
for(i=1;i<3;i++)
{
cout<<"--->";
cin>>b;
if(b==a)
{
cout<<"You won! Congrats!\n";
cout<<"You guessed with "<<i<<" try!\n";
break;
}
if(b!=a)
{
cout<<"No, that's the other number. Try again!\n";
}
}
if(b!=a&&i==3)
{
cout<<"You lose!\n";
}
}
Both codes will compile and run, but the indented code is a lot easier to read. In the second case, it isn’t clear which parenthesis goes with which.
In Python, parentheses aren’t needed, but indentation is. This is what the C++ program would look like in Python:
from random import randint
print("Guess a number game!")
a = randint(1, 11)
print("AI conceived a number from 1 to 10")
print("Enter your guess and press <Enter>")
for i in range(3):
b = int(input("-->"))
if a == b:
print("You won! Congrats!")
print(f"You guessed with {i+1} try!")
break
else:
print("No, that's the other number. Try again!")
else:
print("You lose!")
Guess a number game!
AI conceived a number from 1 to 10
Enter your guess and press <Enter>
-->4
You won! Congrats!
You guessed with 1 try!
However, there is a downside to this beauty. If you make a mistake in the indentation, the program will be inconsistent, which will lead to errors when it’s running.
Perhaps, this is a better option than changing the indentation and not getting the error, but changing the meaning of the program.
The error IndentationError: unexpected indent is one that results from wrong indentation. It happens when there are no keywords in front of the indentation. Here’s an example:
name = "John Smith"
print("Hi, ", name)
File "<ipython-input-2-0ae5732b16d5>", line 2
print("Hi, ", name)
^
IndentationError: unexpected indent
Python expects a keyword line to come before an indented line. List of keywords followed by an indented line:
- class: class definition
- def: function definition
- for: a loop with a parameter
- while: a loop with a condition
- if, elif, else: conditional operator
- try, except, finally: exception handling
- with: a context operator
Python warns you if it finds a line that’s indented, but the previous line doesn’t have these keywords.
How to Solve IndentationError: unexpected indent error in Python
You’ll get a similar error if you don’t indent after a keyword, here’s an example:
for _ in range(10):
print("Hello!")
File "<ipython-input-33-2c027d903716>", line 2
print("Hello!")
^
IndentationError: expected an indented block
IndentationError: expected an indented block happens when you start a construct that assumes you have at least one indented block, but you didn’t indent this.
This is an easy fix. Just indent a block that’s inside a loop or other appropriate construction.
Python uses spaces for indentation, and tabs are automatically converted to four spaces in Python 3 editors.
Another feature is that the number of indent spaces can be any, but inside the block they’re the same.
Since using different numbers of indentations can be confusing, PEP8 recommends exactly four spaces per level of indentation:
a = -1
if a > 0:
print("Positive")
elif a < 0:
print("Negative")
else:
print("Zero")
Negative
This code is possible, it won’t cause an error, but it’ll make your code look terrible to people who’ll read it later.
Often, the IndentationError: unexpected indent error shows up when copying code from any source.
This is a reason why you shouldn’t mindlessly copy-paste code from somewhere.When you borrow code, it’s always best to retype it.
So there won’t be as many errors when you run this code later. And you better understand what you copied.
Even in your very first program, you can get this error if you copy the code along with the layout characters:
print("Hello")
File "<ipython-input-16-c3b57afc4f5f>", line 2
print("Hello")
^
IndentationError: unexpected indent
Another copying error can happen when you edit your code in a text editor without the ability to replace tabs with 4 spaces, such as Notepad++, and use both tabs and spaces for indentation.
This error is the hardest to figure out because it looks like the code’s on the same line.
The first line has a tab and the second has 4 spaces, which is an entirely different level of indentation for a Python interpreter:
print("Hello")
print("World!")
For this error, you can either remove or replace all of the indents, or enable service characters, in Notepad++ this looks like this:
Now you can just replace the tabs with spaces.
How to Solve IndentationError: unindent does not match any outer indentation level in Python
Another error that happens when copying code or when your attention wanders is IndentationError: unindent does not match any outer indentation level. Let’s look at some code that causes such an error:
a = 2
b = 3
for i in range(b):
if a < i:
print("Less")
else:
print("More")
print("Round ", i, " finished!")
Draw vertical lines along the indentation levels. We have three indentation levels here: –
- Original (no indentation)
- First level is the block inside the loop
- Second level is the block inside the conditional statement
When the lines are drawn, it becomes obvious that the indentation is not in line with the print statement. This line doesn’t belong to any of the existing indentation levels.
You need one more space, then the code will run:
a = 1
b = 3
for i in range(b):
if a < i:
print("Less")
else:
print("More")
print("Round ", i, " finished!")
More
Round 0 finished!
More
Round 1 finished!
Less
Round 2 finished!
One way to get around this kind of error is to use automatic code formatters based on PEP8 standards, like autopep8 or Black.
These projects are not primarily intended to fix bugs, but to bring the code up to PEP8 standard, and to maintain code consistency in the project.
When you start out with Python, it is helpful to use these utilities to make beautiful code. But you shouldn’t just do this carelessly. Pay attention to the inaccuracies that such utilities fix.
How to Solve IndentationError: unexpected unindent in Python
A much rarer error is IndentationError: unexpected unindent. Using the try-except operator causes it only under certain conditions.
If you write try, you have to include the except keyword. But if you have just a try without an except, you get SyntaxError: invalid syntax:
try:
print(0)
print(1)
But you’ll get an IndentationError: unexpected unindent if you try to use try-except inside a function, loop, condition, or context.
The Python interpreter walks through the code and finds the try keyword, and searches down the except keyword lines at the same indentation level.
If it doesn’t find it, then it means the try-except operator hasn’t finished yet. Until the whole thing’s done, a line with a lower indentation level cannot appear. Here’s an example:
def multiply_by_two(x):
try:
return 2 * x
multiply_by_two(3)
This error is much less common and harder to find. Try must always have at least one except. If you don’t need to do anything on an exception, use the pass keyword.
def multiply_by_two(x):
try:
return 2 * x
except:
pass
multiply_by_two(3)
6
This isn’t great, but it is syntactically correct.
Use accurate error definitions in your try-except statements, and don’t use empty excepts. If you’re trying to handle an exception, use at least BaseException.
Here’s more Python support:
- 9 Examples of Unexpected Character After Line Continuation Character
- 3 Ways to Solve Series Objects Are Mutable and Cannot be Hashed
- How to Solve ‘Tuple’ Object Does Not Support Item Assignment
- How to Solve SyntaxError: Invalid Character in Identifier
- ImportError: Attempted Relative Import With No Known Parent Package
- How to Solve ImportError: Attempted Relative Import With No Known Parent Package (Python)
- SyntaxError: Invalid Character in Identifier: How to Solve? (Python)
- How to Solve ‘Tuple’ Object Does Not Support Item Assignment (Python)
- 3 Ways to Solve Series Objects Are Mutable and Cannot be Hashed (Python)
- 9 Examples of Unexpected Character After Line Continuation Character (Python)