September 8, 2026
IndentationError in Python: The Real Causes (and How to Stop Hitting It)
Unlike most languages, Python uses indentation itself to define code blocks — no curly braces, no begin/end keywords. That makes code readable, but it also means a single misplaced space can genuinely crash your program before it even runs.
def greet(name):
print("Hello")
print(name) File "script.py", line 3
print(name)
^
IndentationError: unexpected indentThe two real causes
- Mixing tabs and spaces — a line indented with a tab looks identical to one indented with spaces in most editors, but Python treats them as different characters
- Inconsistent indentation within the same block — like the example above, where the second print() line is indented two extra spaces for no reason
In the example above, the problem is exactly that: print(name) is indented further than print("Hello"), even though both lines are meant to belong to the same function body.
The fix
Once both lines inside greet() use identical indentation, the error disappears and the function runs normally.
Most code editors can be configured to show whitespace characters and convert tabs to spaces automatically — turning that on is the single best way to stop this error before it happens. For more on how Python uses indentation to structure code, see the Conditional Statements lesson in our free Python course.