PYTHON Reference Guide
Revision Time: 4 mins

Python Syntax Reference

Core Python language constructs — variables, control flow, comprehensions, and modern syntax.

Variables & Types
Return: None

Define named bindings with dynamic typing.

Used In: Every Python script.

Syntax signature:x = value
Code snippet:
python
name = 'Alex'
age = 30
height = 5.9
is_active = True
print(type(name), type(age))
Expected Output:<class 'str'> <class 'int'>

Time Complexity: O(1)

Common Mistakes: Confusing assignment (=) with equality comparison (==).

Related Methods: type(), isinstance()

Remember: Python is dynamically typed — variables can be reassigned to different types. Use type hints for clarity in larger codebases.
Comments
Return: None

Document code inline or across blocks using # and docstrings.

Used In: All scripts and modules.

Syntax signature:# single line """multi-line docstring"""
Code snippet:
python
# Calculate daily revenue
def revenue(price, qty):
    """Return total revenue from price and quantity."""
    return price * qty
Expected Output:N/A

Time Complexity: O(1)

Common Mistakes: Leaving stale or misleading comments — update comments when you update code.

Remember: Use docstrings for functions/classes and # for inline logic notes.
Input / Output
Return: str / None

Read user input from stdin and print output to stdout.

Used In: CLI tools, interactive scripts.

Syntax signature:input(prompt) / print(*args, sep, end)
Code snippet:
python
name = input('Enter name: ')
print(f'Hello, {name}!')
print('a', 'b', 'c', sep='-')
Expected Output:Hello, Alex! a-b-c

Time Complexity: O(1)

Common Mistakes: Forgetting to cast input() to int when reading numbers — causes TypeError in arithmetic.

Remember: input() always returns a string — cast to int() or float() for numeric operations.
f-Strings
Return: str

Embed expressions directly inside string literals for readable formatting.

Used In: Log messages, report formatting, SQL query building.

Syntax signature:f'{expression}'
Code snippet:
python
name = 'Alex'
sal = 95000
print(f'{name} earns ${sal:,}')
print(f'2 + 2 = {2 + 2}')
Expected Output:Alex earns $95,000 2 + 2 = 4

Time 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

Remember: Use :.2f for fixed decimals, :, for thousand separators, and !r for repr output.
if / elif / else
Return: None

Execute conditional branches based on Boolean expressions.

Used In: Business logic, routing, validation.

Syntax signature:if cond: ... elif cond2: ... else: ...
Code snippet:
python
score = 82
if score >= 90:
    grade = 'A'
elif score >= 75:
    grade = 'B'
else:
    grade = 'C'
print(grade)
Expected Output:B

Time Complexity: O(1)

Common Mistakes: Using multiple separate if statements instead of elif when conditions are mutually exclusive — all branches execute independently.

Remember: Python evaluates elif chains top-down and stops at the first truthy condition.
for loop
Return: None

Iterate over any iterable (list, range, dict, file lines, etc.).

Used In: ETL row processing, batch jobs, file iteration.

Syntax signature:for item in iterable:
Code snippet:
python
employees = ['Alice', 'Bob', 'Carol']
for emp in employees:
    print(f'Processing: {emp}')
Expected Output:Processing: Alice Processing: Bob Processing: Carol

Time Complexity: O(N)

Related Methods: enumerate(), zip(), range()

Remember: Prefer for loops over while loops for iterables — they are safer (no infinite loop risk) and more Pythonic.
while loop
Return: None

Repeat a block of code as long as a condition remains True.

Used In: Retry logic, polling, streaming consumption.

Syntax signature:while condition:
Code snippet:
python
retries = 0
while retries < 3:
    print(f'Attempt {retries + 1}')
    retries += 1
Expected Output:Attempt 1 Attempt 2 Attempt 3

Time Complexity: O(N)

Common Mistakes: Forgetting to update the loop variable, causing an infinite loop.

Remember: Always ensure the loop condition eventually becomes False, or add a break — infinite loops crash processes.
break / continue / pass
Return: None

Control loop flow: exit early, skip iteration, or placeholder do-nothing.

Used In: Early exit on error, skipping invalid records.

Syntax signature:break / continue / pass
Code snippet:
python
for x in range(10):
    if x == 3:
        continue  # skip 3
    if x == 6:
        break     # stop at 6
    print(x)
Expected Output:0 1 2 4 5

Time Complexity: O(1)

Common Mistakes: Using break inside a nested loop — it only exits the innermost loop, not all loops.

Remember: pass is useful as a placeholder in empty function or class bodies that you plan to implement later.
match-case (Python 3.10+)
Return: None

Structural pattern matching — a modern replacement for if/elif chains.

Used In: HTTP status routing, command dispatch, event handling.

Syntax signature:match subject: case pattern: ...
Code snippet:
python
status = 'error'
match status:
    case 'ok':
        print('Success')
    case 'error':
        print('Failed')
    case _:
        print('Unknown')
Expected Output:Failed

Time Complexity: O(1)

Related Methods: if/elif/else

Remember: The _ wildcard acts like a default/else case. match-case supports matching lists, dicts, and class instances.
List Comprehension
Return: List[T]

Build a new list by applying an expression to each element of an iterable.

Used In: Filtering rows, transforming fields, building query params.

Syntax signature:[expr for item in iterable if condition]
Code snippet:
python
salaries = [40000, 75000, 120000, 55000]
high = [s for s in salaries if s > 60000]
print(high)
Expected Output:[75000, 120000]

Time Complexity: O(N)

Related Methods: filter(), map()

Comparison:

List comprehension vs map(): comprehension is more readable; map() is slightly faster for simple function calls.

Remember: More readable and faster than an equivalent for-loop with append(). Keep them on one line for clarity.
Dictionary Comprehension
Return: Dict[K, V]

Build a dictionary from an iterable in a single concise expression.

Used In: Building config maps, lookup tables from CSV rows.

Syntax signature:{key_expr: val_expr for item in iterable if condition}
Code snippet:
python
employees = [('Alice', 90000), ('Bob', 75000)]
sal_map = {name: sal for name, sal in employees if sal > 80000}
print(sal_map)
Expected Output:{'Alice': 90000}

Time Complexity: O(N)

Related Methods: dict(), zip()

Remember: Ideal for inverting dicts, building lookup tables, or transforming key-value structures.
Unpacking
Return: None

Assign multiple variables from an iterable in one statement.

Used In: Tuple unpacking from DB rows, CSV field parsing.

Syntax signature:a, b, c = iterable first, *rest = iterable
Code snippet:
python
name, role, dept = ('Alice', 'Engineer', 'DE')
print(name, role)

first, *rest = [10, 20, 30, 40]
print(first, rest)
Expected Output:Alice Engineer 10 [20, 30, 40]

Time Complexity: O(N)

Common Mistakes: Mismatched left-side count and right-side length raises ValueError.

Remember: Use *rest (starred unpacking) to capture the remainder of a sequence into a list.
Walrus Operator (:=)
Return: T

Assign and return a value inside an expression (assignment expression).

Used In: while loops, if checks that reuse computed values.

Syntax signature:variable := expression
Code snippet:
python
import re
line = 'Error: disk full at 99%'
if m := re.search(r'\d+', line):
    print(f'Found number: {m.group()}')
Expected Output:Found number: 99

Time Complexity: O(1)

Common Mistakes: Overusing := in complex nested expressions reduces readability.

Remember: Avoids calling the same expression twice — compute once, use immediately in the condition.
Ternary Operator
Return: T

Inline conditional expression that returns one of two values.

Used In: Inline value selection, default assignment.

Syntax signature:value_if_true if condition else value_if_false
Code snippet:
python
score = 72
result = 'Pass' if score >= 60 else 'Fail'
print(result)
Expected Output:Pass

Time Complexity: O(1)

Related Methods: if/else

Remember: Keep ternary expressions short. If logic is complex, use a regular if/else block for clarity.