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.
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, andclassall 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
returninside a function block and gettingNoneback 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