Code Block

Python SELF EN
Level 4 , Lesson 1
Available

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

x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")

x = 10
if x > 5:
    print("x is greater than 5")
else:
    print("x is not greater than 5")

When there are multiple nested ifs, it’s very easy to make mistakes:

Incorrect Correct

x = 20
y = 30
if x > 10:
    if y > 20:
    print("y is greater than 20")
else:
print("x is not greater than 10")

x = 20
y = 30
if x > 10:
    if y > 20:
        print("y is greater than 20")
else:
    print("x is not greater than 10") 

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.

2
Task
Python SELF EN, level 4, lesson 1
Locked
The Indenter
The Indenter
2
Task
Python SELF EN, level 4, lesson 1
Locked
Indentation Overdrive
Indentation Overdrive
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION