Python Syntax Guide
Fundamentals Deep Dive
Python Syntax: Readable, strict, and predictable
Master the whitespace-sensitive syntax that differentiates Python from brace-heavy languages. Learn the token types, statement boundaries, and formatting conventions that make codebases consistent.
The whitespace contract
- Python uses indentation to define code blocks. Four spaces is the community standard (enforced by Black).
- Mixing tabs and spaces raises
TabError. Configure your editor to insert spaces automatically. - Continuation lines inside parentheses, brackets, or braces don't require trailing backslashes.
result = (
user.first_name.title()
+ " "
+ user.last_name.title()
)
Statements & expressions
| Concept | Description |
|---|---|
| Simple statement | Fits on one logical line (x = 3, print("hi")). |
| Compound statement | Includes a header + indented block (e.g., if, for, with). |
| Expression | Anything that returns a value (literals, function calls, comprehensions). |
Know when to reach for colons (:) – they always terminate the header of compound statements.
Keywords you can't use as identifiers
| Keyword | Purpose |
|---|---|
| def | Define a function |
| class | Define a class |
| if / elif / else | Conditional branching |
| for / while | Loops |
| try / except / finally | Error handling |
| match / case | Structural pattern matching |
| import / from | Module loading |
| with | Context managers |
| lambda | Anonymous functions |
| yield | Generator control |
Keywords are reserved; do not use them as variable or function names.
Comments and docstrings
- Single-line comment:
# explain why - Block comments: stack multiple single-line comments
- Docstrings: triple quotes directly under a definition
def fetch_user(user_id: str) -> dict:
"""Retrieve a user profile from the API."""
...
Structural patterns to master
Conditional blocks
if balance <= 0:
raise ValueError("Overdrawn")
elif balance < 100:
print("Low funds")
else:
print("All good")
Pattern matching (3.10+)
match payload:
case {"type": "user", "id": user_id}:
handle_user(user_id)
case {"type": "order", "id": order_id}:
handle_order(order_id)
case _:
log.warning("Unknown payload")
Linting + formatting
- Use Black for formatting (88 character lines).
- Use Ruff or Flake8 to catch unused imports, shadowed variables, etc.
- Add an
.editorconfigto enforce indentation and newline rules across editors.
Next up in your learning path
Frequently Asked Questions
Do I need semicolons in Python?
Semicolons are optional and only useful when chaining multiple short statements on one line. Prefer one statement per line for readability.
How do I continue a long statement?
Wrap the statement in parentheses, brackets, or braces. Python automatically continues lines inside those delimiters without requiring `\`.
What is the best way to comment code?
Explain intent—not mechanics. Use docstrings for modules/classes/functions. Keep comments short and update them when logic changes.