Home
Search
Python IndentationErrorUnderstand the cause of IndentationError. Determine how to fix this error.
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.
SyntaxError
Error
Example. 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.
Tip To fix this program, we can change the two print() statements to be indented the same number of characters.
Console, print
# 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.
But The print calls are in separate blocks. For this reason the program executes. It raises no errors.
Thus The important part of indentation is consistency within blocks. It can vary between different blocks, one after another.
# Correct. for n in range(0, 1): print(n) # Correct but different. for n in range(0, 1): print(n)
0 0
Summary. 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.
Home
© 2007-2022 sam allen.
see site info on the changelog.