IndentationError: unexpected indent
IndentationError: unexpected indent
DodaTech
2 min read
IndentationError: unexpected indent means Python found a line with extra whitespace that doesn’t match the expected indentation level. Python uses indentation to define code blocks — consistency is critical.
What It Means
Unlike most languages that use braces or keywords, Python uses indentation to determine which statements belong to which block. Any inconsistency — extra spaces, missing spaces, or a mix of tabs and spaces — triggers this error.
Why It Happens
- Mixing tabs and spaces (the most common cause)
- Extra spaces at the start of a line that shouldn’t be indented
- Inconsistent indentation levels within the same block
- A code editor that inserts tabs when you press Tab, while the rest of the file uses spaces
How to Fix It
Step 1: Use spaces consistently (4 spaces per level)
# BAD — mixing tabs and spaces
def hello():
print("Hello") # 4 spaces
print("World") # 1 tab (looks aligned but isn't)
# GOOD — all spaces (4 per level)
def hello():
print("Hello")
print("World")Step 2: Configure your editor to convert tabs to spaces
Most editors have a setting for this:
VS Code: "editor.insertSpaces": true, "editor.tabSize": 4
PyCharm: Settings → Code Style → Python → "Use tab character" unchecked
Sublime: "translate_tabs_to_spaces": trueStep 3: Re-indent the entire file
Run the reindent script or use an auto-formatter:
# Install and run Black (auto-formatter)
pip install black
black your_file.py
# Or use autopep8
pip install autopep8
autopep8 --in-place your_file.pyStep 4: Check for mixed indentation in your code
# BAD — inconsistent levels
if True:
print("Indented OK")
print("One extra space") # unexpected indent
# GOOD
if True:
print("Indented OK")
print("Also OK")Step 5: Look for unexpected indentation after comments
A stray space before a line that starts a new block can cause this:
# BAD
def my_func():
pass
print("outside function") # This line has a leading space!
# GOOD
def my_func():
pass
print("outside function") Previous
File cannot be loaded because running scripts is disabled
Next
java.lang.ClassNotFoundException
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro