This page was last reviewed on May 26, 2022.
Dot Net Perls
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.
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.
# 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 26, 2022 (rewrite).
© 2007-2024 Sam Allen.