for (int i = 0; i < 5; i++) {
cout << i << "\n";
}
Unlike other languages, Python uses indentation for code blocks. So the above code can simply be written in python as,
for i in range(5):
print(i)
A block is a combination of statements(discussed in previous part). Code block is written as group of statements in order to perform specific operation. Usually it consists of at least one statement and of declarations for the block, depending on the programming or scripting language. Generally, blocks can contain other blocks inside as well, this is called as nested block structure.
In above example,
- Initially we declared variables x and y with their values. This will be our first code block.
- Later we started for loop which is a second code block, so anything that is part of this block, we added whitespaces and then wrote the statements.
- Furthermore, inside for loop, we added if statement which adds nested code block inside for loop, hence, we added extra whitespaces(indent) to write statements of if statement.
- Similarly, we started else nested block and that followed same rules as as if block.
Indentation considerations:
- Generally 4 whitespaces are used for indentation, but we can also use tabs if required.
- This results into Python programs look similar and consistent.
- Indentation in Python makes the code look neat and clean.
- Incorrect indentation will result into IndentationError.
- The amount of indentation is up to users choice, but it must be consistent throughout the code block.
Example:
If True:
print(“Hello”)
a = 5
print(a)
- E.g. above code can also be written on single line as
if True: print(‘Hello’); a = 5

Leave a comment