IndentationError
A Python program uses indentation to nest blocks. Each statement in a block must have the same indentation level. But separate blocks may use different indents.
An IndentationError
occurs if this rule is broken. Like the SyntaxError
, the program can never be run and there is no way to force the program to run.
This program causes an IndentationError
(unexpected indent). In the for
-loop, 2 print method calls appear. But the second print()
call is indented further to the right than the first.
print()
statements to be indented the same number of characters.# An incorrectly-formatted for-loop. for n in range(0, 1): print(n) print(n) print(n) ^ IndentationError: unexpected indent
Next, we find that indent levels have no requirement to be even throughout a program. In this example, the print-statements are unevenly-indented.
# Correct. for n in range(0, 1): print(n) # Correct but different. for n in range(0, 1): print(n)0 0
Indentation is key in Python—it tells us how blocks are organized. Scope, a related concept, is also determined by indentation. The Python language requires strict indentation.