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.
Table of Contents
Hide
- What are the reasons for IndentationError: unexpected indent?
- Python and PEP 8 Guidelines
- Solving IndentationError: expected an indented block
- Example 1 – Indenting inside a function
- Example 2 – Indentation inside for, while loops and if statement
- Conclusion
Python language emphasizes indentation rather than using curly braces like other programming languages. So indentation matters in Python, as it gives the structure of your code blocks, and if you do not follow it while coding, you will get an indentationerror: unexpected indent.
What are the reasons for IndentationError: unexpected indent?
IndentationError: unexpected indent mainly occurs if you use inconsistent indentation while coding. There are set of guidelines you need to follow while programming in Python. Let’s look at few basic guidelines w.r.t indentation.
Python and PEP 8 Guidelines
- Generally, in Python, you follow the four spaces rule according to PEP 8 standards.
- Spaces are the preferred indentation method. Tabs should be used solely to remain consistent with code that is already indented with tabs.
- Do not mix tabs and spaces. Python disallows the mixing of indentation.
- Avoid trailing whitespaces anywhere because it’s usually invisible and it causes confusion.
Solving IndentationError: expected an indented block
Now that we know what indentation is and the guidelines to be followed, Let’s look at few indentation error examples and solutions.
Example 1 – Indenting inside a function
Lines inside a function should be indented one level more than the “def functionname”.
# Bad indentation inside a function
def getMessage():
message= "Hello World"
print(message)
getMessage()
# Output
File "c:ProjectsTryoutslistindexerror.py", line 2
message= "Hello World"
^
IndentationError: expected an indented block
Correct way of indentation while creating a function.
# Proper indentation inside a function
def getMessage():
message= "Hello World"
print(message)
getMessage()
# Output
Hello World
Example 2 – Indentation inside for, while loops and if statement
Lines inside a for, if, and while statements should be indented more than the line, it begins the statement so that Python will know when you are inside the loop and when you exit the loop.
Suppose you look at the below example inside the if statement; the lines are not indented properly. The print statement is at the same level as the if statement, and hence the IndentationError.
# Bad indentation inside if statement
def getMessage():
foo = 7
if foo > 5:
print ("Hello world")
getMessage()
# Output
File "c:ProjectsTryoutslistindexerror.py", line 4
print ("Hello world")
^
IndentationError: expected an indented block
To fix the issues inside the loops and statements, make sure you add four whitespaces and then write the lines of code. Also do not mix the white space and tabs these will always lead to an error.
# Proper indentation inside if statement
def getMessage():
foo = 7
if foo > 5:
print ("Hello world")
getMessage()
# Output
Hello world
Conclusion
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.
Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
Sign Up for Our Newsletters
Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.
By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.
The IndentationError: Unexpected indent error indicates that you have added an excess indent in the line that the python interpreter unexpected to have. An unexpected indent in the Python code causes this indentation error. To overcome the Indentation error, ensure that the code is consistently indented and that there are no unexpected indentations in the code. This would fix the IndentationError: Unexpected indent error.
The IndentationError: Unexpected indent error occurs when you use too many indent at the beginning of the line. Make sure your code is indented consistently and that there are no unexpected indent in the code to resolve Indentation error. Python doesn’t have curly braces or keyword delimiter to differentiate the code blocks. In python, the compound statement and functions requires the indent to be distinguished from other lines. The unexpected indent in python causes IndentationError: Unexpected indent error.
The indent is known as the distance or number of empty spaces between the start of the line and the left margin of the line. Indents are not considered in the most recent programming languages such as java, c++, dot net, etc. Python uses the indent to distinguish compound statements and user defined functions from other lines.
Exception
The error message IndentationError: Unexpected indent indicates that there is an excess indent in the line that the python interpreter unexpected to have. The indentation error will be thrown as below.
File "/Users/python/Desktop/test.py", line 2
print "end of program";
^
IndentationError: unexpected indent
Root Cause
The root cause of the error message “IndentationError: Unexpected indent” is that you have added an excess indent in the line that the python interpreter unexpected to have. In order to resolve this error message, the unexpected indent in the code, such as compound statement, user defined functions, etc. must be removed.
Solution 1
The unexpected indent in the code must be removed. Walk through the code to trace the indent. If any unwanted indent is found, remove it. The lines inside blocks such as compound statements and user defined functions will normally have excess indents, spaces, tabs. This error “IndentationError: unexpected indent” is resolved if the excess indents, tabs, and spaces are removed from the code.
Program
print "a is greater";
print "end of program";
Output
File "/Users/python/Desktop/test.py", line 2
print "end of program";
^
IndentationError: unexpected indent
Solution
print "a is greater";
print "end of program";
Output
a is greater
end of program
[Finished in 0.0s]
Solution 2
In the sublime Text Editor, open the python program. Select the full program by clicking on Cntr + A. The entire python code and the white spaces will be selected together. The tab key is displayed as continuous lines, and the spaces are displayed as dots in the program. Stick to any format you wish to use, either on the tab or in space. Change the rest to make uniform format. This will solve the error.
Program
a=10;
b=20;
if a > b:
print "Hello World"; ----> Indent with tab
print "end of program"; ----> Indent with spaces
Solution
a=10;
b=20;
if a > b:
print "Hello World"; ----> Indent with tab
print "end of program"; ----> Indent with tab
Solution 3
In most cases, this error would be triggered by a mixed use of spaces and tabs. Check the space for the program indentation and the tabs. Follow any kind of indentation. The most recent python IDEs support converting the tab to space and space to tabs. Stick to whatever format you want to use. This is going to solve the error.
Check the option in your python IDE to convert the tab to space and convert the tab to space or the tab to space to correct the error.
Solution 4
In the python program, check the indentation of compound statements and user defined functions. Following the indentation is a tedious job in the source code. Python provides a solution for the indentation error line to identify. To find out the problem run the python command below. The Python command shows the actual issue.
Command
python -m tabnanny test.py
Example
$ python -m tabnanny test.py
'test.py': Indentation Error: unindent does not match any outer indentation level (<tokenize>, line 3)
$
Solution 5
There is an another way to identify the indentation error. Open the command prompt in Windows OS or terminal command line window on Linux or Mac, and start the python. The help command shows the error of the python program.
Command
$python
>>>help("test.py")
Example
$ python
Python 2.7.16 (default, Dec 3 2019, 07:02:07)
[GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.37.14)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> help("test.py")
problem in test - <type 'exceptions.IndentationError'>: unindent does not match any outer indentation level (test.py, line 3)
>>>
Use exit() or Ctrl-D (i.e. EOF) to exit
>>> ^D
![]()
![]()
Fluent Programming|
Python language emphasizes indentation rather than using curly braces like other programming languages. So indentation matters in Python, as it gives the structure of your code blocks, and if you do not follow it while coding, you will get an indentationerror: unexpected indent.
What are the reasons for IndentationError: unexpected indent?
IndentationError: unexpected indent mainly occurs if you use inconsistent indentation while coding. There are set of guidelines you need to follow while programming in Python. Let’s look at few basic guidelines w.r.t indentation.
*Python and PEP 8 Guidelines *
- Generally, in Python, you follow the four spaces rule according to PEP 8 standards.
- Spaces are the preferred indentation method. Tabs should be used solely to remain consistent with code that is already indented with tabs.
- Do not mix tabs and spaces. Python disallows the mixing of indentation.
- Avoid trailing whitespaces anywhere because it’s usually invisible and it causes confusion.
Solving IndentationError: expected an indented block
Now that we know what indentation is and the guidelines to be followed, Let’s look at few indentation error examples and solutions.
Example 1 – Indenting inside a function
Lines inside a function should be indented one level more than the “def functionname”.
# Bad indentation inside a function
def getMessage():
message= "Hello World"
print(message)
getMessage()
# Output
File "c:ProjectsTryoutslistindexerror.py", line 2
message= "Hello World"
^
IndentationError: expected an indented block
# Proper indentation inside a function
def getMessage():
message= "Hello World"
print(message)
getMessage()
# Output
Hello World
Enter fullscreen mode
Exit fullscreen mode
Example 2 – Indentation inside for, while loops and if statement
Lines inside a for, if, and while statements should be indented more than the line, it begins the statement so that Python will know when you are inside the loop and when you exit the loop.
Suppose you look at the below example inside the if statement; the lines are not indented properly. The print statement is at the same level as the if statement, and hence the IndentationError.
# Bad indentation inside if statement
def getMessage():
foo = 7
if foo > 5:
print ("Hello world")
getMessage()
# Output
File "c:ProjectsTryoutslistindexerror.py", line 4
print ("Hello world")
^
IndentationError: expected an indented block
Enter fullscreen mode
Exit fullscreen mode
To fix the issues inside the loops and statements, make sure you add four whitespaces and then write the lines of code. Also do not mix the white space and tabs these will always lead to an error.
# Proper indentation inside if statement
def getMessage():
foo = 7
if foo > 5:
print ("Hello world")
getMessage()
# Output
Hello world
Enter fullscreen mode
Exit fullscreen mode
Conclusion
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.
The post IndentationError: unexpected indent appeared first on Fluent Programming.
Stop sifting through your feed.
Find the content you want to see.
Change your feed algorithm by adjusting your experience level and give weights to the tags you follow.
IndentationErrors serve two purposes: they help make your code more readable and ensure the Python interpreter correctly understands your code. If you add in an additional space or tab where one is not needed, you’ll encounter an “IndentationError: unexpected indent” error.
In this guide, we discuss what this error means and why it is raised. We’ll walk through an example of this error so you can figure out how you can fix it in your program.
Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Access exclusive scholarships and prep courses
Select your interest
First name
Last name
Phone number
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
IndentationError: unexpected indent
An indent is a specific number of spaces or tabs denoting that a line of code is part of a particular code block. Consider the following program:
def hello_world():
print("Hello, world!")
We have defined a single function: hello_world(). This function contains a print statement. To indicate to Python this line of code is part of our function, we have indented it.
You can indent code using spaces or tabs, depending on your preference. You should only indent code if that code should be part of another code block. This includes when you write code in:
- An “if…else” statement
- A “try…except” statement
- A “for” loop
- A “function” statement
Python code must be indented consistently if it appears in a special statement. Python enforces indentation strictly.
Some programming languages like JavaScript do not enforce indentation strictly because they use curly braces to denote blocks of code. Python does not have this feature, so the language depends heavily on indentation.
The cause of the “IndentationError: unexpected indent” error is indenting your code too far, or using too many tabs and spaces to indent a line of code.
The other indentation errors you may encounter are:
- Unindent does not match any other indentation level
- Expected an indented block
An Example Scenario
We’re going to build a program that loops through a list of purchases that a user has made and prints out all of those that are greater than $25.00 to the console.
To start, let’s define a list of purchases:
purchases = [25.50, 29.90, 2.40, 57.60, 24.90, 1.55]
Next, we define a function to loop through our list of purchases and print the ones worth over $25 to the console:
def show_high_purchases(purchases):
for p in purchases:
if p > 25.00:
print("Purchase: ")
print(p)
The show_high_purchases() function accepts one argument: the list of purchases through which the function will search. The function iterates through this list and uses an if statement to check if each purchase is worth more than $25.00.
If a purchase is greater than $25.00, the statement Purchase: is printed to the console. Then, the price of that purchase is printed to the console. Otherwise, nothing happens.
Before we run our code, call our function and pass our list of purchases as a parameter:
show_high_purchases(purchases)
Let’s run our code and see what happens:
File "main.py", line 7 print(p) ^ IndentationError: unexpected indent
Our code does not run successfully.
The Solution
As with any Python error, we should read the full error message to see what is going on. The problem appears to be on line 7, which is where we print the value of a purchase.
if p > 25.00:
print("Purchase: ")
print(p)
We have incidentally indented the second print() statement. This causes an error because our second print() statement is not part of another block of code. It is still part of our if statement.
To solve this error, we need to make sure that we consistently indent all our print() statements:
if p > 25.00:
print("Purchase: ")
print(p)
Both print() statements should use the same level of indentation because they are part of the same if statement. We’ve made this revision above.
Let’s try to run our code:
Purchase: 25.5 Purchase: 29.9 Purchase: 57.6
Our code successfully prints out all the purchases worth more than $25.00 to the console.
Conclusion
“IndentationError: unexpected indent” is raised when you indent a line of code too many times. To solve this error, make sure all of your code uses consistent indentation and that there are no unnecessary indents.
Now you’re ready to fix this error like a Python expert!
Home > Data Science > Indentation Error in Python: Causes, How to Solve, Benefits
As an interpreted, high-level and general-purpose programming language, Python increasingly garners accolades as the programming world’s most promising, leading and emerging platforms. Python is nothing without its ingenious design philosophy.
A key characteristic is an emphasis drawn to the notable use of significant indentation to enhance code-readability. The illustration highlighted below briefly outlines Python’s design philosophy’s bulwarks as twenty aphorisms, alluded to by Tim Peters, long-term Pythoneer, who eventually became one of Python’s most prolific and tenacious core developers.
A Brief Introduction to Python
Before we delve into the specific technicalities underlying the indentation error in Python, we must get acquainted with Python’s fundamentals and the need for indentation. Doing so will not only help you gain a better appreciation of the error itself but offer an insight into the advantages that programmers gain by effectively choosing to resolve the same.
The inception of Python as a multi-paradigm programming language can be traced back to the year 1991. Since then, programmers have continually adapted Python’s core wireframe to suit a range of user-specific needs, such as data science and web and mobile development.
Now, we all know that attempting to comprehend illegible handwriting is painstakingly tricky and often infuriating. Similarly, an unreadable and unstructured code is plain and simple, unacceptable in the programming world. This is where the notion of PEP or Python Enhancement Proposal comes to the programmer’s rescue. PEP to the Python Community is akin to a shared Google Doc for the general populace.
It is a continually updated descriptive mandate that keeps the Python programming community comprehensively informed of features and updates to improve code readability. By Guido van Rossum, Barry Warsaw and Nick Coghlan in 2001, the PEP 8 is referred to as Python’s style code.
Our learners also read – python online course free!
What is Indentation?
It is primarily known that Python is a procedural language, and therefore, an indentation in Python is used to segregate a singular code into identifiable groups of functionally similar statements. The majority of the programming languages, including C, C++ and JAVA, employ curly braces’ {}’ to define a code block. Python marks a deviation from this design and prefers the use of indentation.
Syntax of Indentation
According to the conventions outlined by PEP 8 whitespace ethics, every new iteration (i.e., a block of code) should start with an indentation, and the ending of the code should be the first line that is not indented. The common practice to execute an indentation is four white spaces or a single tab character, with areas being largely preferred over tabs.
As discussed earlier, the leading whitespaces at the start of a line determine the line’s indentation level. To group the statements for a particular code block, you will have to increase the indent level. Similarly, to close the grouping, you will have to reduce the indent level.
Checkout: 42 Exciting Python Project Topic & Ideas
Causes of Indentation Error in Python
The ‘Indentation Error: Expected an indented block’ does not discriminate between users. Whether you are a novice at Python programming or an experienced software developer, this is bound to happen at some point in time. In Python, since all the code you type is arranged via correct whitespaces, if at any instance in the code, you have an incorrect indentation, the overall code with not run, and the interpreter will return an error function. To know exactly what to keep an eye out for, the following lists some of the common causes of an indentation error in Python:
1. The simultaneous use of tabs and space while coding. It can be argued that in theory, both tabs and spaces serve the same purpose, but let us consider this from the perspective of the interpreter. If white spaces and tabs are used inconsistently and interchangeably, it creates ambiguity. This will result in the interpreter getting confused between which alteration to use and eventually returning an indentation error in Python.
2. You have unintentionally placed an indentation in the wrong place or an absence of tabs or white spaces between code lines. Since Python adheres to strict guidelines to arrange written codes, an indentation in the wrong place will inevitably return an error. For example, the first line of Python should not be indented.
3. Occasionally, while finishing an overdue, exceptionally long program, you might unknowingly miss out on indenting compound statement functions such as for, while and if. This will again lead to an indentation error. This is the most basic need for indentation when using Python and needs to be rigorously practised to master.
4. If you have forgotten to use indentation when working with user-defined functions or different classes, an error is likely to pop up.
upGrad’s Exclusive Data Science Webinar for you –
How upGrad helps for your Data Science Career?
Explore our Popular Data Science Courses
How to solve an indentation error in Python?
1. Check for wrong white spaces or tabs. Unfortunately, there is no quick fix to an indentation error. Since the code is yours, the fact remains that you will have to assess each line to identify erroneous instances individually. However, since lines of code are arranged in blocks, the process is relatively simple. For example, if you have used the ‘if’ statement in a particular sequence, you can cross-check if you have remembered to indent the following line.
2. Be certain that the indentation for a specific block remains the same throughout the code, even if a new block is introduced in the middle. Check for inconsistencies in the indentation.
If the above manual solutions did not work for you, and you are having a hard time figuring out where you missed the indentation, then follow these steps:
3. Go to your code editor settings and enable the option that seeks to display tabs and whitespaces. With this feature enabled, you will see single small dots, where each dot represents a tab/white space. If you notice a drop is missing where it shouldn’t be, then that line probably has an indentation error.
4. Use the Python interpreter built-in Indent Guide. Arguably, this method is highly inefficient for several code lines. However, since it takes you through each line and shows you exactly where your error lies, it is the surest way to find and fix all errors.
Also Read: Top 12 Fascinating Python Applications in Real World
Read our popular Data Science Articles
Benefits of Indentation
Readability and consistency are essential for any good code. Following the PEP 8 whitespace, ethics should thus be non-negotiable. It logically substantiates your code, thereby contributing to a more pleasant coding experience. Additionally, if you follow this stylistic guideline where readability is your de facto, people who are unknown to you, but are interested in your work, will understand your code with ease.
Disadvantages of Indentation
- If the code is large and the indentation is corrupted, it can be tedious to fix indentation errors. This is usually when a code is copying from an online source, Word document or PDF file.
- Popular programming languages typically use braces for indentation. For programmers just beginning to use Python, adjusting to the idea of using whitespaces for indentation can be difficult.
Top Data Science Skills to Learn in 2022
Summing Up
All that lies between you and a well-written code is an indentation, and all that lies between you, your well-written code and its seamless execution is an indentation error. Now, all humans make mistakes. All programmers are humans. Therefore, all programmers make mistakes. But an indentation error can easily be resolved. All you need to do is breathe and take your space.
I hope you will learn a lot while working on these python projects. If you are curious about learning data science to be in front of fast-paced technological advancements, check out upGrad & IIIT-B’s Executive PG Programme in Data Science and upskill yourself for the future.
What errors can I get due to indentation in Python?
Python determines when code blocks begin and stop by looking at the space at the beginning of the line. You may encounter the following Indentation errors:
1. Unexpected indent — This line of code has more spaces at the beginning than the one before it, but the one before it does not begin a subblock. In a block, all lines of code must begin with the same string of whitespace.
2. Unindent does not correspond to any of the outer indentation levels — This line of code contains less spaces at the beginning than the previous one, but it also does not match any other block.
3. An indented block was expected — This line of code begins with the same number of spaces as the previous one, yet the previous line was supposed to begin a block (e.g., if/while/for statement, function definition).
How do you fix inconsistent tabs and spaces in indentation Spyder?
Tabs and spaces are two separate characters that appear on the screen as whitespace. The issue is that there is no consensus on how big a tab character should be, thus some editors display it as taking up 8 spaces, others as 4 spaces, and others as 2, and it’s also customizable.
When you code but one line is indented with a tab and the other with spaces, Python throws an error, despite the fact that it seems good in the editor (but it won’t look fine if you double the width of a tab; now the tab lines will be indented two levels).
To avoid this problem, go to your text editor’s options and enable the convert tabs to spaces feature, which replaces the tab character with n space characters, where n is the tab width your editor uses.
How do you show indents on Spyder?
Select your code and press Tab or Shift + Tab to indent or un-indent it. Other tools for altering your code can be found in the Edit section.
Want to share this article?

Prepare for a Career of the Future
If you are new to coding or an experienced coder, you might have come across indentation error in python. It looks silly but it can pause the entire process and take good amount of time to fix it. I can help you saving some of your precious time. So, lets dive little deeper into it and understand what is indentation and how to fix it
Python is a procedural language. An indentation in Python is used to segregate a singular code into identifiable groups of functionally similar statements. The indentation error can occur when the spaces or tabs are not placed properly. There will not be an issue if the interpreter does not find any issues with the spaces or tabs. If there is an error due to indentation, it will come in between the execution and can be a show stopper.
Python follows the PEP8 whitespace ethics while arranging its code and therefore it is suggested that there should be 4 whitespaces between every iteration and any alternative that doesn’t have this will return an error.
Below are some of the common causes of an indentation error in Python:
-
While coding you are using both the tab as well as space. While in theory both of them serve the same purpose, if used alternatively in a code, the interpreter gets confused between which alteration to use and thus returns an error.
-
While programming you have placed an indentation in the wrong place. Since python follows strict guidelines when it comes to arranging the code, if you placed any indentation in the wrong place, the indentation error is mostly inevitable.
-
Sometimes in the midst of finishing a long program, we tend to miss out on indenting the compound statements such as for, while and if and this in most cases will lead to an indentation error.
-
Last but not least, if you forget to use user defined classes, then an indentation error will most likely pop up.
Errors due to indentation in Python:
Python determines when code blocks begin and stop by looking at the space at the beginning of the line. You may encounter the following Indentation errors:
1. Unexpected indent — This line of code has more spaces at the beginning than the one before it, but the one before it does not begin a sub block. In a block, all lines of code must begin with the same string of whitespace.
2. Unindent does not correspond to any of the outer indentation levels — This line of code contains less spaces at the beginning than the previous one, but it also does not match any other block.
3. An indented block was expected — This line of code begins with the same number of spaces as the previous one, yet the previous line was supposed to begin a block (e.g., if/while/for statement, function definition).
Few tips to solve an indentation error in Python:
1. While there is no quick fix to this problem, one thing that you need to keep in mind while trying to find a solution for the indentation error is the fact that you have to go through each line individually and find out which one contains the error.
In Python, all the lines of code are arranged according to blocks, so it becomes easier for you to spot an error. For example, if you have used the if statement in any line, the next line must definitely have an indentation.
Take a look at the example below.

If you need guidance on how the correct form of indentation will look like, take a look at the example below.

2. Go to your code editor settings and enable the option that seeks to display tabs and whitespaces. With this feature enabled, you will see single small dots, where each dot represents a tab/white space. If you notice a drop is missing where it shouldn’t be, then that line probably has an indentation error.
For Pycharm, please go to file — settings — editor — code style — python
3. Use the Python interpreter built-in Indent Guide. It takes you through each line and shows you exactly where your error lies, it is the surest way to find and fix all errors.
Conclusion:
Getting errors are inevitable part of programming, so is debugging. One cannot ignore indentation error while working with python but above tips show that it can be easily resolved. Hope this information makes your life little easy and programming journey more exciting.
References:
https://www.edureka.co/blog/indentation-error-in-python/
Python is a programming language that relies a lot on spacing. Proper spacing and indentation are essential in Python for the program to work without errors. Spacing or indentation in Python indicates a block of code.
In this article, you’ll learn how to rectify the unexpected indent error in Python.
Rectify the IndentationError: unexpected indent Error in Python
An unexpected indent occurs when we add an unnecessary space or tab in a line of the code block. The message IndentationError: unexpected indent is shown when we run the code if this type of error is contained within your program.
The following code below shows an example of when an unexpected indent error occurs.
def ex1():
print("Hello Internet")
print("It's me")
ex1()
Output:
File "<string>", line 3
print("It's me")
^
IndentationError: unexpected indent
In the example code above, we define a function ex1(), which contains two print statements. However, the second print statement has an unnecessary space or tab before it.
This code produces an unexpected indent error in line 3 as it encounters the additional space before the print("It's me") statement.
The following code rectifies the error contained in the previous program.
def ex1():
print("Hello Internet")
print("It's me")
ex1()
Output:
Python is a programming language that strictly enforces indentation. Indentation also increases the readability of the code.
Indentation can be done in Python using either spaces or the tab button; choosing which one depends entirely on the user. The Python code needs to be indented in some cases where one part of the code needs to be written in a block.
Some cases where we need to use indentation and might get an unexpected indent error if we don’t do that are:
- The
if-elseconditional statement - A
foror awhileloop - A simple
functionstatement - A
try...exceptstatement
Программирование, Python, Учебный процесс в IT, Блог компании SkillFactory
Рекомендация: подборка платных и бесплатных курсов PR-менеджеров — https://katalog-kursov.ru/

Выяснить, что означают сообщения об ошибках Python, может быть довольно сложно, когда вы впервые изучаете язык. Вот список распространенных ошибок, которые приводят к сообщениям об ошибках во время выполнения, которые могут привести к сбою вашей программы.
1) Пропуск “:” после оператора if, elif, else, for, while, class или def. (Сообщение об ошибке: “SyntaxError: invalid syntax”)
Пример кода с ошибкой:
if spam == 42
print('Hello!')
2) Использование = вместо ==. (Сообщение об ошибке: “SyntaxError: invalid syntax”)
= является оператором присваивания, а == является оператором сравнения «равно». Пример кода с ошибкой:
if spam = 42:
print('Hello!')
3) Использование неправильного количества отступов. (Сообщение об ошибке: «IndentationError: unexpected indent» и «IndentationError: unindent does not match any outer indentation level» и «IndentationError: expected an indented block»)
Помните, что отступ увеличивается только после оператора, оканчивающегося на “:” двоеточие, и впоследствии должен вернуться к предыдущему отступу.
Пример кода с ошибкой:
print('Hello!')
print('Howdy!')
… еще:
if spam == 42:
print('Hello!')
print('Howdy!')
… еще:
if spam == 42:
print('Hello!')
4) Забыть вызвать len() в операторе цикла for. (Сообщение об ошибке: “TypeError: 'list' object cannot be interpreted as an integer”)
Обычно вы хотите перебирать индексы элементов в списке или строке, что требует вызова функции range(). Просто не забудьте передать возвращаемое значение len(someList) вместо передачи только someList.
Пример кода с ошикой:
spam = ['cat', 'dog', 'mouse']
for i in range(spam):
print(spam[i])
(UPD: как некоторые указали, вам может понадобиться только for i in spam: вместо приведенного выше кода. Но вышесказанное относится к очень законному случаю, когда вам нужен индекс в теле цикла, а не только само значение.)
5) Попытка изменить строковое значение. (Сообщение об ошибке: “TypeError: 'str' object does not support item assignment”)
Строки являются неизменным типом данных. Пример кода с ошибкой:
spam = 'I have a pet cat.'
spam[13] = 'r'
print(spam)
Пример правильного варианта:
spam = 'I have a pet cat.'
spam = spam[:13] + 'r' + spam[14:]
print(spam)
6) Попытка объединить не строковое значение в строковое значение. (Сообщение об ошибке: “TypeError: Can't convert 'int' object to str implicitly”)
Пример кода с ошибкой:
numEggs = 12
print('I have ' + numEggs + ' eggs.')
Правильный вариант:
numEggs = 12
print('I have ' + str(numEggs) + ' eggs.')
… или:
numEggs = 12
print('I have %s eggs.' % (numEggs))
7) Пропуск кавычки, в начале или конце строкового значения. (Сообщение об ошибке: “SyntaxError: EOL while scanning string literal”)
Пример кода с ошикой:
print(Hello!')
… еще:
print('Hello!)
...еще:
myName = 'Al'
print('My name is ' + myName + . How are you?')
8) Опечатка в переменной или имени функции. (Сообщение об ошибке: “NameError: name 'fooba' is not defined”)
Пример кода с ошибкой:
foobar = 'Al'
print('My name is ' + fooba)
...еще:
spam = ruond(4.2)
...еще:
spam = Round(4.2)
9) Опечатка в названии метода. (Сообщение об ошибке: “AttributeError: 'str' object has no attribute 'lowerr'”)
Пример кода с ошибкой:
spam = 'THIS IS IN LOWERCASE.'
spam = spam.lowerr()
10) Выход за пределы массива. (Сообщение об ошибке: “IndexError: list index out of range”)
Пример кода с ошибкой:
spam = ['cat', 'dog', 'mouse']
print(spam[6])
11) Использование несуществующего ключа словаря. (Сообщение об ошибке: “KeyError: 'spam'”)
Пример кода с ошибкой:
spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam['zebra'])
12) Попытка использовать ключевые слова Python в качестве переменной (Сообщение об ошибке: “SyntaxError: invalid syntax”)
Ключевые слова Python (также называются зарезервированные слова) не могут быть использованы для названия переменных. Ошибка будет со следующим кодом:
class = 'algebra'
Ключевые слова Python 3: and, as, assert, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield
13) Использование расширенного оператора присваивания для новой переменной. (Сообщение об ошибке: “NameError: name 'foobar' is not defined”)
Не думайте, что переменные начинаются со значения, такого как 0 или пустая строка. Выражение с расширенным оператором как spam += 1 эквивалентно spam = spam + 1. Это означает, что для начала в spam должно быть какое-то значение.
Пример кода с ошибкой:
spam = 0
spam += 42
eggs += 42
14) Использование локальных переменных (с таким же именем как и у глобальной переменной) в функции до назначения локальной переменной. (Сообщение об ошибке: “UnboundLocalError: local variable 'foobar' referenced before assignment”)
Использовать локальную переменную в функции, имя которой совпадает с именем глобальной переменной, довольно сложно. Правило таково: если переменной в функции когда-либо назначается что-то, она всегда является локальной переменной, когда используется внутри этой функции. В противном случае, это глобальная переменная внутри этой функции.
Это означает, что вы не можете использовать ее как глобальную переменную в функции до ее назначения.
Пример кода с ошибкой:
someVar = 42
def myFunction():
print(someVar)
someVar = 100
myFunction()
15) Попытка использовать range() для создания списка целых чисел. (Сообщение об ошибке: “TypeError: 'range' object does not support item assignment”)
Иногда вам нужен список целочисленных значений по порядку, поэтому range() кажется хорошим способом создать этот список. Однако вы должны помнить, что range() возвращает «объект диапазона», а не фактическое значение списка.
Пример кода с ошибкой:
spam = range(10)
spam[4] = -1
То что вы хотите сделать, выглядит так:
spam = list(range(10))
spam[4] = -1
(UPD: Это работает в Python 2, потому что Python 2’s range() возвращает список значений. Но, попробовав сделать это в Python 3, вы увидите ошибку.)
16) Нет оператора ++ инкремента или -- декремента. (Сообщение об ошибке: “SyntaxError: invalid syntax”)
Если вы пришли из другого языка программирования, такого как C++, Java или PHP, вы можете попытаться увеличить или уменьшить переменную с помощью ++ или --. В Python таких операторов нет.
Пример кода с ошибкой:
spam = 0
spam++
То что вы хотите сделать, выглядит так:
spam = 0
spam += 1
17) UPD: как указывает Luchano в комментариях, также часто забывают добавить self в качестве первого параметра для метода. (Сообщение об ошибке: «TypeError: TypeError: myMethod() takes no arguments (1 given)»)
Пример кода с ошибкой:
class Foo():
def myMethod():
print('Hello!')
a = Foo()
a.myMethod()
Краткое объяснение различных сообщений об ошибках приведено в Приложении D книги «Invent with Python».

Узнайте подробности, как получить востребованную профессию с нуля или Level Up по навыкам и зарплате, пройдя онлайн-курсы SkillFactory:
- Курс «Профессия Data Scientist» (24 месяца)
- Курс «Профессия Data Analyst» (18 месяцев)
- Курс «Python для веб-разработки» (9 месяцев)
Читать еще
- 450 бесплатных курсов от Лиги Плюща
- Бесплатные курсы по Data Science от Harvard University
- 30 лайфхаков чтобы пройти онлайн-курс до конца
- Самый успешный и самый скандальный Data Science проект: Cambridge Analytica