Published on

6. Python blocks

Authors

6. What are Python blocks and how do you define them?

What are Python Blocks?

A block in Python is a group of statements that are executed together. Blocks define the body of control structures like functions, loops, conditionals, classes, etc.


How to Define Blocks in Python?

Python uses indentation (whitespace at the beginning of a line) to define blocks instead of braces {} like in many other languages.


Key points:

  • A block starts after a colon (:).
  • All lines within the block must be indented by the same amount (usually 4 spaces).
  • The block ends when the indentation returns to the previous level.

Examples:

1. If-Else Block:

if x > 0:
    print("Positive")
    print("Number is greater than zero")
else:
    print("Non-positive")

2. Function Block:

def greet(name):
    print(f"Hello, {name}!")
    print("Welcome!")

3. Loop Block:

for i in range(3):
    print(i)
    print("Looping...")

Why indentation matters?

if True:
print("This will cause an IndentationError")

This code will throw an IndentationError because the print statement is not indented inside the if block.


Summary:

  • Blocks are groups of statements executed together.
  • Defined by indentation after a colon :.
  • Indentation level controls block boundaries.
  • Proper indentation is mandatory in Python syntax.