Problem
A Python script stops before its first line runs, and the Run tool window or the terminal shows an error such as:
File "C:\path\to\script.py", line 3
if marks >90:
IndentationError: unexpected indent
The same cause produces these related errors:
IndentationError: expected an indented block after 'if' statement on line 2
IndentationError: unindent does not match any outer indentation level
TabError: inconsistent use of tabs and spaces in indentation
This article applies when the file in the traceback is the project's own script. When the file is under the IDE's helpers directory, such as plugins/python-ce/helpers/syspath.py, see Cannot set up a Python SDK due to invalid SDK error.
Cause
Python uses the whitespace at the start of each line to group statements into blocks. The Python interpreter checks the indentation before it runs the file, so the error occurs in every editor and terminal, not only in PyCharm. The usual mistakes are:
- A line is indented, but no statement above it opens a block. For example, an
ifstatement is indented under a top-levelprint()call. - The body of an
if,elif,else,for,whileordefstatement is not indented more than the statement itself. - The statements of one
if/elif/elsechain start at different columns. - One block mixes tabs and spaces.
Resolution
- Open the file at the line number from the traceback.
- Move every statement of one chain, such as
if,elifandelse, to the same column. - Indent the body of each statement by 4 spaces more than the statement.
- Replace tabs with spaces in that block.
- Run the script again. When a new indentation error appears, repeat the steps for the line it names.
Example of a script that fails with IndentationError: unexpected indent on line 3:
marks = int(input())
print("the marks is", marks)
if marks > 90:
print("A")
elif marks > 80:
print("B")
else:
print("fail")
The same script with correct indentation:
marks = int(input())
print("the marks is", marks)
if marks > 90:
print("A")
elif marks > 80:
print("B")
else:
print("fail")
Comments
0 comments
Please sign in to leave a comment.