Python Blocks and Indentation
In Python, a block is a group of statements that belong together.
Python uses indentation to define these blocks instead of braces
such as { }.
What is a Block in Python?
A block is a group of statements executed together when a condition, loop, function or other control structure is used.
if age >= 18:
print("You are eligible to vote.")
print("You are an adult.")
The two print() statements are part of the if
block because they have the same indentation.
What is Indentation?
Indentation means leaving spaces at the beginning of a line. Python uses indentation to identify the statements belonging to a block. Usually, 4 spaces are used for one level of indentation.
if marks >= 40:
print("Pass")
print("Congratulations")
Indentation with if-else
marks = 65
if marks >= 40:
print("Pass")
else:
print("Fail")
Pass
Nested Blocks
A block can contain another block. This is called a nested block.
marks = 85
if marks >= 40:
if marks >= 80:
print("Grade A")
else:
print("Grade B")
Grade A
Indentation with Loops
Statements inside a loop must be indented.
for i in range(1, 4):
print(i)
1 2 3
Incorrect Indentation
Incorrect or inconsistent indentation can produce an
IndentationError.
if age >= 18:
print("Eligible")
The print() statement must be indented because it belongs
to the if block.
Important Rules of Indentation
- Use indentation to define a block.
- Use consistent indentation throughout the program.
- Four spaces are commonly used for one indentation level.
- Statements at the same indentation level belong to the same block.
- Do not mix spaces and tabs unnecessarily.