- IndentationError: expected an indented block
- Exception
- Root Cause
- Solution 1
- Solution 2
- Program
- Solution
- Solution 3
- Program
- Output
- Solution
- Output
- Solution 4
- program
- Solution
- Output
- Solution 5
- Program
- Output
- Solution
- Output
- Solution 6
- Command
- Example
- Solution 7
- Command
- Example
- IndentationError: expected an indented block
- Cause 1: Unindented Statement
- Solution
- Cause 2: Empty Suite
- Solution
- Cause 3: Unindented Docstring
- Solution
- Summary
- How to Fix the “IndentationError: expected an indented block” Error in Your Python Code
- Why Do You Get the IndentationError in Python?
- Common Cases of Correct Indentation
- If statements
- Functions
IndentationError: expected an indented block
The IndentationError: expected an indented block error indicates that you have an indentation error in the code block, which is most likely caused by a mix of tabs and spaces. The indentation is expected in an indented block. The IndentationError: expected an indented block error happens when you use both the spaces and tabs to indent in your code. The indent is expected in a block. To define a code block, you may use any amount of indent, but the indent must match exactly to be at the same level.
The python IndentationError: expected an indented block error occurs when you forget to indent the statements within a compound statement or within a user-defined function. In python, the expected an indented block error is caused by a mix of tabs and spaces. If you do not have appropriate indents added to the compound statement and the user defined functions, the error IndentationError: expected an indented block will be thrown.
The indent is known as the distance or number of empty spaces between the line ‘s beginning and the line’s left margin. The intent is used in order to make the code appear better and be easier to read. In python, the intent is used to describe the structure of the compound statement and the user-defined functions
Exception
In the compound statement and the user-defined functions, the inside code must be indented consistently. If you failed to add an indent, the error IndentationError: expected an indented block is shown. The error message suggests that the code lacks indentation.
The error IndentationError: expected an indented block is shown to be like the stack trace below. The error message displays the line that the indent is supposed to be added to.
File "/Users/python/Desktop/test.py", line 5 print "hello world"; ^ IndentationError: expected an indented block [Finished in 0.0s with exit code 1]
Root Cause
Python is the sentivite language of indentation. Compound statement and functions require an indent before starting a line. The error message IndentationError: expected and indented block is thrown due to a lack of indent in the line that the python interpreter expects to have.
There’s no syntax or semantic error in your code. This error is due to the style of writing of the program
Solution 1
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 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
The program has no indentation where the python interpreter expects the indentation to have. The blocks are supposed to have an indentation before the beginning of the line. An indentation should be added in line 4 in the example below
Program
a=20; b=10; if a > b: print "hello world";
Output
File "/Users/python/Desktop/test.py", line 5 print "hello world"; ^ IndentationError: expected an indented block
Solution
a=20; b=10; if a > b: print "hello world";
Output
hello world [Finished in 0.0s]
Solution 4
Python may have an incomplete block of statements. There may be a missing statement in the block. Some of the lines may be incomplete or deleted from the program. This is going to throw the indentation error.
Add missing lines to the program or complete the pending programming. This is going to solve the error.
program
a=20; b=10; if a > b: print "hello world"; else:
Solution
a=20; b=10; if a > b: print "hello world"; else: print "hello world in else block";
Output
hello world [Finished in 0.0s]
Solution 5
In the above program, if the else block is irrelevant to logic, remove the else block. This will solve the indent error. The Python interpreter helps to correct the code. Unnecessary code must be removed in the code.
Program
a=20; b=10; if a > b: print "hello world"; else:
Output
File "/Users/python/Desktop/test.py", line 5 print "hello world"; ^ IndentationError: expected an indented block
Solution
a=20; b=10; if a > b: print "hello world";
Output
hello world [Finished in 0.0s]
Solution 6
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
Example
$ python -m tabnanny test.py 'test.py': Indentation Error: unindent does not match any outer indentation level (, line 3) $
Solution 7
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
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 - : unindent does not match any outer indentation level (test.py, line 3) >>> Use exit() or Ctrl-D (i.e. EOF) to exit >>> ^D
IndentationError: expected an indented block
As the error implies, this occurs after statements that require indenting, such as after if statements, for loops and try except exception handling.
Unlike many programming languages that use braces, Python requires indents to determine which code block belongs to a statement. More simply, after detecting the : character in your script, Python will look for an indent.
This lesson will quickly examine a few reasons when this error can occur and how to fix it.
Cause 1: Unindented Statement
Imagine you are looking at sales figures for Company A, which sells software packages. You want to write a script for determining which employees are meeting a certain sales threshold.
Using enumerate , we can iterate through employees and use the index as an ID for each employee. We can then print off a message showing if that employee hit the sales target or not.
The script below shows how we can execute this process:
Although we’ve made the if else loop correctly, the for statement is causing an indentation error. This error is happening because we’ve provided a list for Python to iterate through in our for loop, but it doesn’t know which logic it needs to apply while looping.
The straightforward fix is to add an indent at the line indicated in the error:
Solution
Now that Python has the correct structure, it will check the sales figure for each employee individually and consider if the number is greater than 50 or not. It will then print the corresponding message and move on to the next employee.
Cause 2: Empty Suite
When working on larger scripts, you’ll often anticipate many if elif branches ahead of time by creating a branch and commenting on some logic you plan on filling in later.
Here’s an example using our sales analysis script that we used previously:
In this case, Python throws the error because it’s looking for a code block after the if statement, i.e., what your program should do if the statement is true. The code seems to be structured correctly, but the program will fail to run until the actual code is placed after the if .
Having a statement like this without anything following it is known as an empty suite. A quick fix for this is to use the pass keyword:
Solution
In this situation, the pass keyword allows Python to skip when the if is true. This command bypasses the indentation error, allowing us to work on other areas until we are ready to come back and write the functionality that displays a message.
Cause 3: Unindented Docstring
To keep code well-documented, we can use docstrings at the start of a function, class, or method to quickly say what the code does. This description is to make life easier for yourself and others when reviewing the code later.
To write a docstring, you use two sets of triple apostrophes (»’) or quotes («»»), which makes multi-line comments in Python possible.
The example below shows how we can use a docstring to describe a function to contain the if-else loop we’ve been using in our sales analysis script.
This script crashed because Python is looking for indentation at the start of the function. To fix this, we can add an indent to the docstring. Shown below is this solution in action:
Solution
Note that in this example, using a regular comment (#) to mark the docstring would prevent the indentation error without the need to add an indent. Avoid doing this, though, as it’s best practice to keep docstrings within two sets of triple apostrophes/quotes.
Summary
This error occurs when Python is looking for an indented block of code after certain types of statements. The indented block tells Python that the code within the block is relevant to the statement. This s>tructure is fundamental to the Python programming language, so it’s no surprise incorrectly indenting things can make scripts malfunction! Luckily, this is an easy fix, and in most cases, all you need to do is quickly add an indent in the correct place, and you’ll be good to go.
How to Fix the “IndentationError: expected an indented block” Error in Your Python Code
Indentation is more important in Python than many languages, so much so that it can cause errors. Learn how to deal with the most common problem.
Readers like you help support MUO. When you make a purchase using links on our site, we may earn an affiliate commission. Read More.
Indentation is a vital feature of readable, maintainable code, but few languages enforce it. Python is one of those few.
If Python determines your code is indented incorrectly, you’ll be seeing the “IndentationError” message when you run your code. But how do you fix this, and how do you prevent it in the future?
Why Do You Get the IndentationError in Python?
The “IndentationError: expected an indented block” error is something you’re likely to see when you first start using Python, especially if you’ve come from another programming language.
The specifics of Python’s indentation rules are complex, but they boil down to one thing: indent code in blocks. This goes for functions, if clauses, and so on. Here’s an example of incorrectly formatted Python code:
fname = "Gaurav"
lname = "Siyal"
if fname == "Gaurav" and lname == "Siyal":
print("You're Gaurav")
else:
print("You're somebody else")
When you try to run the above code, you’ll get a message like this:
File «tmp.py», line 5
print(«You’re Gaurav»)
^
IndentationError: expected an indented block
Instead, you should add either a tab or a series of spaces at the start of the two lines that represent blocks:
fname = "Gaurav"
lname = "Siyal"
if fname == "Gaurav" and lname == "Siyal":
print("You're Gaurav")
else:
print("You're somebody else")
If you indent with spaces, you can actually use any number you like, so long as you’re consistent and unambiguous. Most programmers use two, four, or eight spaces.
Common Cases of Correct Indentation
Here are some examples that you can refer to, so you can ensure you’re indenting correctly.
If statements
Indent the block that follows an if statement:
if my_name == "Gaurav":
print("My name is Gaurav")
return True
Functions
The body of a function is a block. You should indent this entire block: