Guide Python Beginner

4.14 Code Blocks

The four kinds of Python code blocks — if, loop, function, and class blocks — and how they all follow the same colon-and-indentation rule.

1 min read

A code block is any indented group of statements introduced by a colon-terminated header line. All four kinds below follow the exact same indentation rule from 4.4 Indentation.

flowchart TD CB["Code Block\n(colon-terminated header\n+ indented body)"] CB --> IF["if Block"] CB --> LOOP["Loop Block"] CB --> FUNC["Function Block"] CB --> CLASS["Class Block"]

if Blocks

if status == "active":
    print("Service is running")

Loop Blocks

for server in ["web01", "web02"]:
    print(f"Checking {server}")

Function Blocks

def is_valid(code):
    return 200 <= code < 300

Class Blocks

class Server:
    def __init__(self, name):
        self.name = name

Quick Interview Answer

“A code block is any colon-terminated header line followed by an indented body — if, for/while, def, and class all use the exact same mechanism. There’s no separate ‘block’ keyword in Python; indentation alone marks where a block starts and ends.”

Common Mistakes

  • Assuming each block type has different indentation rules — they don’t; if, loops, functions, and classes all follow the identical colon + indent pattern.
  • Forgetting a return inside a function block and getting None back instead of the expected value.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form