Python’s conditional constructs enable branching logic, while its style conventions—guided by PEP 8—ensure clarity and maintainability across projects.
Conditional Statements
Python offers several ways to express decision-making logic. Though conceptually similar to C-style syntax, key syntactic and semantic differences exist.
Basic Forms
-
Simple
if:
Requires a colon (:) and indented block. No parentheses around the condition are needed. -
if-elseexpression (ternary operator):
A compact inline form for assigning values based on a Boolean condition: ``` status = "active" if user.is_authenticated else "guest"This is distinct from list comprehensions but shares their emphasis on concision. Avoid nesting complex expressions here; prefer full `if` blocks when readability suffers. -
if-elif-else:
Supports multiple mutually exclusive branches. Unlike C,elifis a single keyword—notelse if. -
match-case(Python 3.10+):
A structural pattern-matching construct that replaces traditionalswitch. It evaluates once and executes only the first matching case: ``` match http_status: case 400: response = "Bad Request" case 401 | 403 | 404: response = "Access Denied" case _: response = "Unknown Error"The `_` wildcard ensures exhaustive coverage, analogous to `default` in other languages.
Structural Patterns
Conditions may be nested, placed side-by-side, or encapsulated in functions for reuse and testability:
def classify_number(x):
if x > 0:
return "positive"
elif x < 0:
return "negative"
else:
return "zero"
PEP 8 Style Essentials
Indentation
- Use four spaces per indentation level—never tabs.
- Consistent indentation defines logical blocks; mismatched indentation raises
IndentationError. - For line continuation inside parentheses, brackets, or braces, align wrapped elements vertically or use a hanging indent with an extra level of indentation.
Line Length and Wrapping
- Limit lines to 79 characters for code (PEP 8 recommendation).
- Prefer implicit line continuation (e.g., within parentheses) over backslash (
\) escapes. - Explicit continuation is required for statements like
assertorwiththat don’t support implicit wrapping.
Whitespace Rules
- No spaces inside
[],(), or{}; e.g.,func(arg), notfunc( arg ). - No space before commas, colons, or semicolons; one space after them.
- In slicing notation, apply uniform spacing around both colons:
data[low : high : step]. - Surround assignment and comparison operators with single spaces:
x = y + 1, notx=y+1.
Comments and Documentation
- Inline comments should explain why, not what.
- Docstrings (triple-quoted strings) are preferred for module, class, and function documentation.
- File-level comments may include authorship, purpose, and creation date—but avoid redundancy with version control metadata.
Naming Conventions
- Use
snake_casefor variables and functions:user_count,calculate_total. - Avoid reserved names (
class,def,print, etc.) as identifiers. - Prefer descriptive, unambiguous names over abbreviations:
max_retriesinstead ofmax_ret.