7.1 The Importance of Indentation
Sometimes you need to group a few commands together. Such a group is called a command block or simply a code block. In Python, code blocks are defined by indentation, which makes the structure of the program clean and readable.
Unlike many other programming languages where code blocks are indicated by braces or keywords, Python uses indentation to separate sequences of instructions, which is known as block structure.
Theoretically, indentation can be done using spaces or tabs. However, PEP 8, the official Python style guide, recommends using 4 spaces for each level of indentation. It’s crucial to use a consistent indentation style throughout the code.
Block Structure:
A code block starts with a statement followed by
a colon (e.g., if
,
for
, while
, def
, class
)
and indentation on the next line.
All statements with the same level of indentation are considered part of one block.
Indentation affects how Python interprets the code. Incorrect use of indentation can lead to IndentationError or change the logic of the program.
7.2 Consistent Amount of Indentation
It is very important for code blocks to have a consistent amount of indentation. Therefore, mixing tab and space characters is highly discouraged. Some editors display a tab as 8 spaces, others as 4. This can lead to errors.
PyCharm solves this problem easily: it inserts 4 spaces every time you press the TAB key on your keyboard. No tab characters — no problem.
Example:
Incorrect | Correct |
|
|
When there are multiple nested ifs, it’s very easy to make mistakes:
Incorrect | Correct |
|
|
You need to clearly understand which if
the else
belongs to, otherwise you risk misplacing the indentation and getting a program that does something entirely different than what you intended.
This mistake is especially common among beginners when they decide to move a ready-made piece of code under an if
. Or transfer a code block from one place to another where a different amount of indentation is required.
Use PyCharm: this IDE is well-aware of these issues and automatically adds the necessary amount of indentation when moving code.
GO TO FULL VERSION