Previous Post
Python Indentation: Complete Rules Explained with Examples
Introduction
Python indentation is not just about code formatting—it’s a core part of Python’s syntax. Unlike many languages that use braces {} to define code blocks, Python relies entirely on indentation to understand structure and flow. A single extra space or missing indent can break your program or, worse, change its logic without showing any error.
In this post, we’ll focus specifically on Python indentation errors—why they happen, how to recognize them, and the exact ways to fix them. From common issues like unexpected indent and expected an indented block to silent logic bugs caused by improper spacing, this guide will help you write cleaner, error-free Python code with confidence.
Error 1: IndentationError
Introduction
IndentationError is one of the most common errors in Python, especially for beginners. It occurs when Python detects incorrect or inconsistent indentation in your code. Since Python uses indentation to define code blocks, even a small spacing mistake can cause this error and prevent the program from running.
This error usually appears when a block of code is missing indentation, has extra indentation, or does not align properly with surrounding code.
Example
if True:
print("Python Indentation Error")Output
IndentationError: expected an indented blockExplanation
In Python, any statement that ends with a colon (:), such as if, for, while, def, or class, must be followed by an indented block.
In the example above, the print() statement is not indented, so Python doesn’t know which code belongs to the if block.
How to Fix This Error
Indent the code inside the block properly. The recommended standard is 4 spaces per indentation level (PEP 8).
Fixed Example
if True:
print("Python Indentation Error")Fixed Example Explanation
Now the print() statement is indented under the if condition. Python clearly understands that this line belongs to the block, so the code runs without errors.if
Tips & Important Notes to Avoid IndentationError
- Always indent code after
if,for,while,def,class,try, andwith. - Use 4 spaces, not tabs (follow PEP 8).
- Never mix tabs and spaces in the same file.
- Configure your editor to show whitespace characters.
- Use a code editor with Python linting (VS Code, PyCharm).
- Be extra careful when copying and pasting code.
Summary
IndentationError happens when Python cannot understand your code’s structure due to incorrect spacing. Consistent indentation and a good editor setup can prevent most of these errors entirely.
Error 2: IndentationError: unexpected indent
Introduction
The IndentationError: unexpected indent occurs when Python finds an indented line where no indentation is expected. In simple terms, Python sees extra spaces at the beginning of a line even though no code block has started.
This error is common when indentation is added accidentally, code is copied from another source, or tabs and spaces are mixed.
Example
print("Start Program")
print("This line causes an error")Output
IndentationError: unexpected indentExplanation
In Python, indentation is only valid after a block-opening statement that ends with a colon (:).
In this example, the first line does not start any block, yet the second line is indented. Python flags this as an error because it does not expect an indented statement here.
How to Fix This Error
Remove the unnecessary indentation or start a proper code block before indenting.
Fixed Example
print("Start Program")
print("This line is now correct")Fixed Example Explanation
Both lines are now aligned at the same indentation level. Since no block is defined, Python correctly executes the code without raising an error.
Tips & Important Notes to Avoid IndentationError
- Only indent code after statements ending with a colon (
:). - Avoid pressing Tab randomly; use consistent spaces.
- Enable “show whitespace” in your editor.
- Auto-format code using tools like
black. - Be cautious when pasting code from websites or documents.
Summary
IndentationError: unexpected indent means Python encountered extra indentation where it shouldn’t exist. Clean alignment and consistent formatting prevent this error completely.
Error 3: IndentationError: expected an indented block
Introduction
The IndentationError: expected an indented block occurs when Python expects a block of indented code but doesn’t find one. This usually happens after statements that must be followed by a block, such as if, for, while, def, class, try, or with.
In simple terms, Python is telling you: “You started a block, but didn’t put anything inside it.”
Example
if True:
print("This will cause an error")Output
IndentationError: expected an indented blockExplanation
The if True: statement ends with a colon, which tells Python that a new code block is starting. However, the next line is not indented, so Python cannot determine the block’s body and raises this error.
How to Fix This Error
Indent the code that belongs to the block. Use 4 spaces for indentation, as recommended by PEP 8.
Fixed Example
if True:
print("This is now correct")Fixed Example Explanation
The print() statement is properly indented, clearly indicating that it belongs to the if block. Python can now interpret the block structure correctly and execute the code.
Tips & Important Notes to Avoid IndentationError
- Use
passif you haven’t written the block logic yet. - Configure your editor to auto-indent code.
- Avoid removing indentation accidentally while editing.
- Review block structures carefully in nested code.
Summary
IndentationError: expected an indented block means a required code block is missing. Proper indentation or using ensures Python understands your program structure.pass
Error 4: TabError: inconsistent use of tabs and spaces
Introduction
TabError: inconsistent use of tabs and spaces occurs when Python detects a mix of tabs and spaces for indentation in the same block of code. Python requires indentation to be consistent, and mixing whitespace types makes it impossible for the interpreter to reliably determine block boundaries.
This error often appears when code is written or edited using different editors or copied from multiple sources.
Example
if True:
↹print("Line with tab indentation")
print("Line with space indentation")Output
TabError: inconsistent use of tabs and spaces in indentationExplanation
Although tabs and spaces may look aligned in some editors, Python treats them differently. In the example above, the first print() line uses a tab, while the second uses spaces. Python sees this as inconsistent indentation within the same block and raises a TabError.
How to Fix This Error
Use only spaces or only tabs for indentation—preferably 4 spaces, as recommended by PEP 8.
Fixed Example
if True:
print("Line with space indentation")
print("Another properly indented line")Fixed Example Explanation
Both lines now use 4 spaces for indentation, making the block consistent. Python can clearly interpret the block structure, so the code runs without errors.
Tips & Important Notes to Avoid IndentationError
- Follow PEP 8: always use 4 spaces for indentation.
- Configure your editor to convert tabs to spaces automatically.
- Enable “show whitespace” to spot hidden tabs.
- Use auto-formatters like
blackorautopep8. - Avoid mixing code from different editors without reformatting.
Summary
TabError occurs when tabs and spaces are mixed in indentation. Consistent use of spaces eliminates this error entirely and improves code readability.
Error 5: IndentationError: unindent does not match any outer indentation level
Introduction
The error IndentationError: unindent does not match any outer indentation level occurs when Python encounters an indentation level that does not align with any previously defined block. This usually happens when indentation is reduced incorrectly or when tabs and spaces are mixed.
In short, Python can’t figure out which block the code belongs to.
Example
if True:
print("Inside if block")
print("Wrong indentation level")Output
IndentationError: unindent does not match any outer indentation levelExplanation
In this example, the first print() statement is indented with 4 spaces, making it part of the if block.
The second statement is indented with 2 spaces, which does not match any valid outer indentation level. Python cannot match this indentation with the original block structure, so it raises the error.print()
How to Fix This Error
Ensure that every unindented or dedented line matches an existing indentation level exactly.
Fixed Example
if True:
print("Inside if block")
print("Correct indentation level")Fixed Example Explanation
The second print() statement is now fully unindented, matching the outer level of the if block. Python can correctly determine the block boundaries, and the code runs without errors.
Tips & Important Notes to Avoid IndentationError
- Always indent and unindent in exact multiples of the same spacing.
- Stick to 4 spaces per indentation level.
- Reformat pasted code before running it.
Summary
This error means Python cannot match your indentation with any known block. Consistent spacing and careful alignment prevent this issue completely.
Error 6: Logical Errors due to Wrong Indentation
Introduction
Logical errors caused by wrong indentation are the most dangerous indentation issues in Python. Unlike other indentation problems, no error message is raised. The program runs successfully, but the output or behavior is incorrect because Python interprets the code structure differently than intended.
These bugs are often hard to detect and can lead to serious issues in real-world applications.
Example
if True:
print("User authenticated")
print("Access granted")
print("Welcome!")Output
User authenticated
Access granted
Welcome!Explanation
Visually, the code may look correct, but the last print() statement is not indented. Python treats it as outside the if block, so it executes every time, regardless of the condition.
The programmer may have intended Welcome! to run only when the condition is true, but due to incorrect indentation, the logic changes silently.
How to Fix This Error
Indent the statement correctly so it belongs to the intended block.
Fixed Example
if True:
print("User authenticated")
print("Access granted")
print("Welcome!")Fixed Example Explanation
All three print() statements are now inside the if block. Python executes them only when the condition is true, restoring the intended program logic.
Tips & Important Notes to Avoid IndentationError
- Always double-check block alignment, especially in
if,for, andwhileblocks. - Write small, readable blocks instead of deeply nested code.
- Use print/debug statements to verify code flow.
- Rely on linters to detect suspicious indentation logic.
Summary
Wrong indentation can silently change program logic without raising errors. Clear formatting, careful reviews, and testing are essential to avoid these hidden bugs.
Error 7: Unexpected Behavior in Loops (Due to Indentation)
Introduction
Unexpected behavior in loops occurs when loop-related code is indented incorrectly. Python does not raise an error in these cases, but the loop may run fewer times, more times, or skip important statements entirely. These issues are subtle and often lead to incorrect results without any warning.
This problem is common in for and while loops when code is unintentionally placed outside the loop body.
Example
for i in range(3):
print(i)
print("Loop running")Output
0
1
2
Loop runningExplanation
The print("Loop running") statement is not indented, so it executes after the loop finishes instead of during each iteration. If the intention was to print this message inside the loop, the indentation is incorrect.
Python follows indentation strictly, not visual intention.
How to Fix This Error
Indent all statements that should run as part of the loop.
Fixed Example
for i in range(3):
print(i)
print("Loop running")Fixed Example Explanation
Now both print() statements are indented under the loop, so they execute during every iteration. The loop behavior matches the intended logic.
Tips & Important Notes to Avoid This Error
- Ensure all loop-related code is indented under the loop.
- Watch out for accidental unindentation while editing.
- Test loop output with small inputs.
Summary
Incorrect indentation in loops can silently change execution flow. Always verify which lines belong inside the loop to avoid unexpected behavior.
Error 8: Editor-Dependent Indentation Issues
Introduction
Editor-dependent indentation issues occur when Python code behaves differently across editors due to hidden whitespace, tab handling, or auto-indent settings. The code may look perfectly aligned in one editor but raise indentation errors or behave unexpectedly in another.
This problem is common when switching editors, collaborating with others, or copying code from the web.
Example
Code written in one editor:
if True:
print("Hello")
print("World")Same code opened in another editor (tabs shown as spaces visually):
if True:
↹print("Hello")
print("World")Output
TabError: inconsistent use of tabs and spaces in indentationExplanation
Some editors automatically insert tabs, while others use spaces. Even if the indentation looks identical on screen, Python detects the difference internally. When mixed indentation reaches the interpreter, it results in errors like TabError or IndentationError.
How to Fix This Error
Normalize indentation by converting all tabs to spaces and enforcing consistent editor settings.
Fixed Example
if True:
print("Hello")
print("World")Fixed Example Explanation
Both lines now use 4 spaces for indentation. The code behaves consistently across all editors and environments.
Tips & Important Notes to Avoid This Error
- Configure your editor to insert spaces instead of tabs.
- Enable visible whitespace.
- Run code in the same environment where it’s written.
- Standardize editor settings in team projects.
Summary
Editor-dependent indentation issues are caused by hidden or inconsistent whitespace. Consistent formatting and proper editor configuration prevent these errors entirely.
Error 9: Indentation Issues in Multiline Statements
Introduction
Indentation issues in multiline statements occur when line breaks, alignment, or indentation are handled incorrectly in expressions that span multiple lines. These problems often appear in function calls, lists, dictionaries, tuples, and long conditional statements.
Such mistakes can raise SyntaxError or cause confusing behavior, even though the code looks visually correct.
Example
total = sum(
[10, 20, 30]
)Output
SyntaxError: invalid syntaxExplanation
In multiline statements, Python expects consistent alignment. In this example, the closing parenthesis is over-indented, breaking the logical structure of the expression. Python cannot match the indentation with the opening statement, resulting in a syntax error.
How to Fix This Error
Align multiline elements properly, usually by aligning closing brackets with the opening statement or keeping a consistent indentation level inside parentheses.
Fixed Example
total = sum(
[10, 20, 30]
)Fixed Example Explanation
The closing parenthesis now aligns correctly with the opening line. Python can interpret the multiline expression without ambiguity, so the code executes successfully.
Tips & Important Notes to Avoid This Error
- Use parentheses for multiline statements instead of backslashes.
- Keep all items vertically aligned.
- Align closing brackets with the opening line.
- Avoid manual spacing for alignment.
Summary
Improper indentation in multiline statements breaks Python’s syntax rules. Consistent alignment and clean formatting ensure readability and error-free execution.
Comparison of Common Python Indentation Errors
The table below compares the most common Python indentation errors, showing how they occur, their impact on execution, and how to fix them quickly.
| Error No. | Error Name | Error Type | When It Occurs | Python Raises Error? | Common Cause | How to Fix |
|---|---|---|---|---|---|---|
| 1 | IndentationError | Runtime / Syntax | General incorrect indentation | âś… Yes | Missing, extra, or inconsistent indentation | Use proper block indentation (4 spaces) |
| 2 | IndentationError: unexpected indent | Syntax | Indentation without starting a block | âś… Yes | Extra spaces before a line | Remove unnecessary indentation |
| 3 | IndentationError: expected an indented block | Syntax | Block statement has no indented body | âś… Yes | Missing indentation after : | Indent block or use pass |
| 4 | TabError: inconsistent use of tabs and spaces | Syntax | Tabs and spaces mixed | âś… Yes | Different editors or copy-paste | Convert tabs to spaces |
| 5 | IndentationError: unindent does not match any outer indentation level | Syntax | Incorrect dedentation | âś… Yes | Wrong indentation level | Align with existing blocks |
| 6 | Logical Errors due to Wrong Indentation | Logical | Code runs but behaves incorrectly | ❌ No | Misplaced indentation | Correct block alignment |
| 7 | Unexpected Behavior in Loops | Logical | Loop code placed outside loop | ❌ No | Incorrect loop indentation | Indent loop body properly |
| 8 | Editor-Dependent Indentation Issues | Environment | Same code fails in different editors | ⚠️ Sometimes | Hidden tabs/spaces | Normalize editor settings |
| 9 | Indentation Issues in Multiline Statements | Syntax | Misaligned multiline expressions | âś… Yes | Incorrect bracket alignment | Align parentheses correctly |
Conclusion
Python indentation is more than a formatting rule—it defines how your code works. As seen throughout this post, even small indentation mistakes can lead to syntax errors, runtime failures, or silent logical bugs that are difficult to detect. Understanding common indentation errors and their causes helps you debug faster and write more predictable code.
Next Post
Python Indentation: Understanding Blocks of Code and Nested Indentation
Suggested Posts
1. Python Indentation: The Complete Guide for Beginners & Developers
2.Python Indentation: Complete Rules Explained with Examples
3: Python Indentation: Understanding Blocks of Code and Nested Indentation
4: Python Indentation: Complete FAQ Guide for Beginners and Developers

3 thoughts on “Python Indentation: Common Errors, Causes, and How to Fix Them”