Indentation refers to the whitespace(s) at the beginning of a statement.
Unlike in other languages where indentation is just used for code clarity, it is a mandatory feature in Python and forms a part of the language's syntax. Improperly indented code will lead to IndentationError
exception.
We use indentation to logically separate blocks of code from one another. It also helps to make code easier to read and understand by visually grouping related statements together and making structural relationships more obvious.
Blocks refer to groups of related statements that are treated as a single unit such as in an if statement, a looping statement, a function declaration, or a class definition. A block of code is typically delimited by a colon( :
), statement(s) following the colon should be indented.
As we said earlier, indentation is mandatory , failing to indent statements of a block will result in an IndentationError
.
The amount of indentation does not matter, however, all statements at one level of indentation must be consistently indented. This means that all statements at the same level of indentation must use the same amount of whitespace, such as a four-space or two-space indentation.
It is a convention to use a four-space indentation meaning that each logical level of indentation is increased by four spaces. This is intended to improve the readability of the code by making it easier to visually distinguish between different levels.
You can use regular whitespace or the tab character for indentation, however, it is important to be consistent with whichever one you choose. Using both in the same code can easily lead to hard-to-debug errors.
Advantages of Indentation
- Indented lines of code helps to make the program easier to read and follow,.
- Proper indentation makes code more organized, making it easier to find and fix errors.
- Indentation helps to make sure the syntactic structure of a program is enforced.
- In Python, indentation is used as an alternative to brackets in other languages. This makes Python code more human-friendly.
Summary on indentation
- Indentation refers to the whitesspaces at the beginning of a statement.
- Any amount of whitespace can be used for indentation, however, the convention is to use four-spaces indentation.
- All statements at one level in a block should be consistently indented i.e they should be indented with equal amount of whitespaces.
- An
IndentationError
exception is raised when code is improperly indented. This can happen when the indentation occur in unexpected place or is missing in a required place.