Python Syntax Reference
Core Python language constructs — variables, control flow, comprehensions, and modern syntax.
Define named bindings with dynamic typing.
Used In: Every Python script.
x = valuename = 'Alex'
age = 30
height = 5.9
is_active = True
print(type(name), type(age))<class 'str'> <class 'int'>Time Complexity: O(1)
Common Mistakes: Confusing assignment (=) with equality comparison (==).
Related Methods: type(), isinstance()
Document code inline or across blocks using # and docstrings.
Used In: All scripts and modules.
# single line
"""multi-line docstring"""# Calculate daily revenue
def revenue(price, qty):
"""Return total revenue from price and quantity."""
return price * qtyN/ATime Complexity: O(1)
Common Mistakes: Leaving stale or misleading comments — update comments when you update code.
Read user input from stdin and print output to stdout.
Used In: CLI tools, interactive scripts.
input(prompt) / print(*args, sep, end)name = input('Enter name: ')
print(f'Hello, {name}!')
print('a', 'b', 'c', sep='-')Hello, Alex!
a-b-cTime Complexity: O(1)
Common Mistakes: Forgetting to cast input() to int when reading numbers — causes TypeError in arithmetic.
Embed expressions directly inside string literals for readable formatting.
Used In: Log messages, report formatting, SQL query building.
f'{expression}'name = 'Alex'
sal = 95000
print(f'{name} earns ${sal:,}')
print(f'2 + 2 = {2 + 2}')Alex earns $95,000
2 + 2 = 4Time Complexity: O(N)
Common Mistakes: Using f-strings in hot loops for heavy string building — use str.join() for better performance.
Related Methods: str.format(), %s formatting
Execute conditional branches based on Boolean expressions.
Used In: Business logic, routing, validation.
if cond:
...
elif cond2:
...
else:
...score = 82
if score >= 90:
grade = 'A'
elif score >= 75:
grade = 'B'
else:
grade = 'C'
print(grade)BTime Complexity: O(1)
Common Mistakes: Using multiple separate if statements instead of elif when conditions are mutually exclusive — all branches execute independently.
Iterate over any iterable (list, range, dict, file lines, etc.).
Used In: ETL row processing, batch jobs, file iteration.
for item in iterable:employees = ['Alice', 'Bob', 'Carol']
for emp in employees:
print(f'Processing: {emp}')Processing: Alice
Processing: Bob
Processing: CarolTime Complexity: O(N)
Related Methods: enumerate(), zip(), range()
Repeat a block of code as long as a condition remains True.
Used In: Retry logic, polling, streaming consumption.
while condition:retries = 0
while retries < 3:
print(f'Attempt {retries + 1}')
retries += 1Attempt 1
Attempt 2
Attempt 3Time Complexity: O(N)
Common Mistakes: Forgetting to update the loop variable, causing an infinite loop.
Control loop flow: exit early, skip iteration, or placeholder do-nothing.
Used In: Early exit on error, skipping invalid records.
break / continue / passfor x in range(10):
if x == 3:
continue # skip 3
if x == 6:
break # stop at 6
print(x)0
1
2
4
5Time Complexity: O(1)
Common Mistakes: Using break inside a nested loop — it only exits the innermost loop, not all loops.
Structural pattern matching — a modern replacement for if/elif chains.
Used In: HTTP status routing, command dispatch, event handling.
match subject:
case pattern:
...status = 'error'
match status:
case 'ok':
print('Success')
case 'error':
print('Failed')
case _:
print('Unknown')FailedTime Complexity: O(1)
Related Methods: if/elif/else
Build a new list by applying an expression to each element of an iterable.
Used In: Filtering rows, transforming fields, building query params.
[expr for item in iterable if condition]salaries = [40000, 75000, 120000, 55000]
high = [s for s in salaries if s > 60000]
print(high)[75000, 120000]Time Complexity: O(N)
Related Methods: filter(), map()
List comprehension vs map(): comprehension is more readable; map() is slightly faster for simple function calls.
Build a dictionary from an iterable in a single concise expression.
Used In: Building config maps, lookup tables from CSV rows.
{key_expr: val_expr for item in iterable if condition}employees = [('Alice', 90000), ('Bob', 75000)]
sal_map = {name: sal for name, sal in employees if sal > 80000}
print(sal_map){'Alice': 90000}Time Complexity: O(N)
Related Methods: dict(), zip()
Assign multiple variables from an iterable in one statement.
Used In: Tuple unpacking from DB rows, CSV field parsing.
a, b, c = iterable
first, *rest = iterablename, role, dept = ('Alice', 'Engineer', 'DE')
print(name, role)
first, *rest = [10, 20, 30, 40]
print(first, rest)Alice Engineer
10 [20, 30, 40]Time Complexity: O(N)
Common Mistakes: Mismatched left-side count and right-side length raises ValueError.
Assign and return a value inside an expression (assignment expression).
Used In: while loops, if checks that reuse computed values.
variable := expressionimport re
line = 'Error: disk full at 99%'
if m := re.search(r'\d+', line):
print(f'Found number: {m.group()}')Found number: 99Time Complexity: O(1)
Common Mistakes: Overusing := in complex nested expressions reduces readability.
Inline conditional expression that returns one of two values.
Used In: Inline value selection, default assignment.
value_if_true if condition else value_if_falsescore = 72
result = 'Pass' if score >= 60 else 'Fail'
print(result)PassTime Complexity: O(1)
Related Methods: if/else