Appendix A: Python Quick Reference

This appendix is a concentrated reference for the Python syntax and patterns covered in this textbook. It is not a tutorial — every item here is explained in detail in the chapter indicated. Use this when you know what you want to do but can't quite remember how to write it.


A.1 Data Types at a Glance

Type Example Literals Mutable? Chapter
int 42, -7, 0b1010, 0xFF No 3
float 3.14, -0.5, 2.0e8 No 3
bool True, False No 3, 4
str "hello", 'world', """multi""" No 3, 7
list [1, 2, 3], [] Yes 8
tuple (1, 2, 3), (), (42,) No 8
dict {"a": 1, "b": 2}, {} Yes 9
set {1, 2, 3}, set() Yes 9
frozenset frozenset({1, 2}) No 9
NoneType None No 6

Truthiness Rules (Ch. 4): These values are falsy: False, 0, 0.0, "", [], (), {}, set(), None. Everything else is truthy.


A.2 Operators

Arithmetic Operators

Operator Name Example Result
+ Addition 7 + 3 10
- Subtraction 7 - 3 4
* Multiplication 7 * 3 21
/ True division 7 / 3 2.333...
// Floor division 7 // 3 2
% Modulo 7 % 3 1
** Exponentiation 2 ** 10 1024

Operator precedence (highest to lowest): ** then * / // % then + -. Use parentheses when in doubt.

Augmented Assignment

Operator Equivalent to
x += 5 x = x + 5
x -= 5 x = x - 5
x *= 5 x = x * 5
x /= 5 x = x / 5
x //= 5 x = x // 5
x %= 5 x = x % 5
x **= 5 x = x ** 5

Comparison Operators

Operator Meaning Example
== Equal to x == 5
!= Not equal to x != 5
< Less than x < 5
> Greater than x > 5
<= Less than or equal x <= 5
>= Greater than or equal x >= 5

Chained comparisons: 1 < x < 10 is valid Python (equivalent to 1 < x and x < 10).

Boolean Operators

Operator Meaning Short-circuits?
and Both must be true Yes — stops at first False
or At least one must be true Yes — stops at first True
not Inverts truth value No

Precedence: not > and > or.

Identity and Membership

Operator Usage Notes
is x is None Tests identity (same object in memory)
is not x is not None Negated identity test
in "a" in "abc" Membership test — works on strings, lists, dicts, sets
not in 5 not in [1, 2, 3] Negated membership

A.3 String Methods (Ch. 7)

Case Methods

Method Example Result
s.upper() "hello".upper() "HELLO"
s.lower() "HELLO".lower() "hello"
s.title() "hello world".title() "Hello World"
s.capitalize() "hello world".capitalize() "Hello world"
s.swapcase() "Hello".swapcase() "hELLO"

Search Methods

Method Returns Notes
s.find(sub) Index of first match, or -1
s.rfind(sub) Index of last match, or -1
s.index(sub) Index of first match Raises ValueError if not found
s.count(sub) Number of non-overlapping occurrences
s.startswith(prefix) bool
s.endswith(suffix) bool

Modification Methods (Return New Strings)

Method Example Result
s.strip() " hi ".strip() "hi"
s.lstrip() " hi ".lstrip() "hi "
s.rstrip() " hi ".rstrip() " hi"
s.replace(old, new) "hello".replace("l", "r") "herro"
s.split(sep) "a,b,c".split(",") ["a", "b", "c"]
s.split() "a b c".split() ["a", "b", "c"]
sep.join(iterable) ", ".join(["a", "b"]) "a, b"
s.center(width) "hi".center(10) " hi "
s.ljust(width) "hi".ljust(10) "hi "
s.rjust(width) "hi".rjust(10) " hi"
s.zfill(width) "42".zfill(5) "00042"

Testing Methods

Method Returns True when
s.isalpha() All characters are letters
s.isdigit() All characters are digits
s.isalnum() All characters are letters or digits
s.isspace() All characters are whitespace
s.isupper() All cased characters are uppercase
s.islower() All cased characters are lowercase

String Indexing and Slicing

s = "Python"
s[0]        # 'P'       — first character
s[-1]       # 'n'       — last character
s[1:4]      # 'yth'     — index 1 up to (not including) 4
s[:3]       # 'Pyt'     — first three characters
s[3:]       # 'hon'     — from index 3 to end
s[::2]      # 'Pto'     — every other character
s[::-1]     # 'nohtyP'  — reversed

A.4 List Methods (Ch. 8)

Adding Elements

Method Effect Returns
lst.append(x) Adds x to end None
lst.extend(iterable) Adds all items from iterable None
lst.insert(i, x) Inserts x at index i None

Removing Elements

Method Effect Returns
lst.pop() Removes and returns last item The item
lst.pop(i) Removes and returns item at i The item
lst.remove(x) Removes first occurrence of x None (raises ValueError if absent)
lst.clear() Removes all items None
del lst[i] Deletes item at index i (statement, not method)

Searching and Counting

Method Returns
lst.index(x) Index of first x (raises ValueError if absent)
lst.count(x) Number of occurrences of x

Ordering

Method Effect Notes
lst.sort() Sorts in place (ascending) Returns None
lst.sort(reverse=True) Sorts in place (descending)
lst.sort(key=func) Sorts by key function e.g., key=len, key=str.lower
lst.reverse() Reverses in place
sorted(lst) Returns a new sorted list Does NOT modify original

Copying

shallow = lst.copy()          # or lst[:]
import copy
deep = copy.deepcopy(lst)     # for nested structures

List Comprehensions

[expression for item in iterable]
[expression for item in iterable if condition]
[f(x) for x in range(10) if x % 2 == 0]

A.5 Dictionary Methods (Ch. 9)

Accessing

Method Returns Notes
d[key] Value Raises KeyError if key absent
d.get(key) Value or None
d.get(key, default) Value or default

Adding / Updating

Method Effect
d[key] = value Sets key to value (adds or overwrites)
d.update(other_dict) Merges other_dict into d
d.setdefault(key, val) Sets d[key] = val only if key absent; returns d[key]

Removing

Method Returns Notes
d.pop(key) Value Raises KeyError if absent
d.pop(key, default) Value or default
del d[key] Raises KeyError if absent
d.clear() None Removes all items

Iterating

for key in d:                  # iterate over keys
for key in d.keys():           # same as above (explicit)
for value in d.values():       # iterate over values
for key, value in d.items():   # iterate over key-value pairs

Dictionary Comprehensions

{key_expr: val_expr for item in iterable}
{k: v for k, v in d.items() if v > 0}

Useful Standard Library

from collections import defaultdict, Counter, OrderedDict

counts = Counter(["a", "b", "a", "c", "a", "b"])
# Counter({'a': 3, 'b': 2, 'c': 1})

dd = defaultdict(list)
dd["key"].append("val")       # no KeyError — auto-creates empty list

A.6 Set Methods (Ch. 9)

Creating Sets

s = {1, 2, 3}                # set literal
s = set()                     # empty set (NOT {} — that's a dict)
s = set([1, 2, 2, 3])        # from iterable — duplicates removed

Modifying

Method Effect
s.add(x) Adds x to set
s.remove(x) Removes x (raises KeyError if absent)
s.discard(x) Removes x (no error if absent)
s.pop() Removes and returns an arbitrary element
s.clear() Removes all elements

Set Operations

Operation Method Operator
Union a.union(b) a \| b
Intersection a.intersection(b) a & b
Difference a.difference(b) a - b
Symmetric difference a.symmetric_difference(b) a ^ b
Subset test a.issubset(b) a <= b
Superset test a.issuperset(b) a >= b

A.7 Control Flow Syntax

Conditionals (Ch. 4)

if condition:
    # body
elif other_condition:
    # body
else:
    # body

match/case (Ch. 4, Python 3.10+)

match value:
    case "option1":
        # body
    case "option2" | "option3":
        # matches either
    case _:
        # wildcard / default

for Loop (Ch. 5)

for item in iterable:
    # body

for i in range(n):             # 0, 1, ..., n-1
for i in range(start, stop):   # start, start+1, ..., stop-1
for i in range(start, stop, step):

for i, item in enumerate(lst):             # index + value
for a, b in zip(list1, list2):             # parallel iteration

while Loop (Ch. 5)

while condition:
    # body

# Input validation pattern
while True:
    value = input("Enter a number: ")
    if value.isdigit():
        break
    print("Invalid — try again.")

Loop Control

Statement Effect
break Exit the loop immediately
continue Skip to the next iteration
else (on a loop) Runs if the loop completes without break

A.8 Function Syntax (Ch. 6)

Defining Functions

def function_name(param1, param2):
    """Docstring describing the function."""
    # body
    return result

# Default parameters
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

# *args — variable positional arguments
def average(*numbers):
    return sum(numbers) / len(numbers)

# Keyword-only arguments
def connect(host, *, port=80, timeout=30):
    pass

# Type hints (informational only — not enforced)
def add(a: int, b: int) -> int:
    return a + b

Returning Multiple Values

def min_max(numbers):
    return min(numbers), max(numbers)

lo, hi = min_max([3, 1, 4, 1, 5])

Lambda Functions (Ch. 19)

square = lambda x: x ** 2
sorted(words, key=lambda w: len(w))

A.9 Class Syntax (Ch. 14-16)

Basic Class

class Dog:
    species = "Canis familiaris"    # class attribute

    def __init__(self, name, age):
        self.name = name            # instance attribute
        self.age = age

    def __str__(self):
        return f"{self.name} ({self.age} years)"

    def __repr__(self):
        return f"Dog(name={self.name!r}, age={self.age})"

    def __eq__(self, other):
        return self.name == other.name and self.age == other.age

    def bark(self):
        return f"{self.name} says Woof!"

Inheritance (Ch. 15)

class GuideDog(Dog):
    def __init__(self, name, age, handler):
        super().__init__(name, age)
        self.handler = handler

    def bark(self):                  # method overriding
        return f"{self.name} stays quiet (working dog)"

Abstract Base Classes (Ch. 15)

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14159 * self.radius ** 2

Dataclasses (Ch. 16)

from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float
    label: str = ""

Properties (Ch. 14)

class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius

    @property
    def fahrenheit(self):
        return self._celsius * 9 / 5 + 32

    @fahrenheit.setter
    def fahrenheit(self, value):
        self._celsius = (value - 32) * 5 / 9

A.10 File I/O Patterns (Ch. 10)

Reading Files

# Read entire file
with open("data.txt", "r") as f:
    content = f.read()

# Read line by line (memory-efficient)
with open("data.txt", "r") as f:
    for line in f:
        line = line.strip()
        # process line

# Read all lines into a list
with open("data.txt", "r") as f:
    lines = f.readlines()

Writing Files

# Write (overwrites existing content)
with open("output.txt", "w") as f:
    f.write("Hello\n")
    f.write("World\n")

# Append (adds to end)
with open("output.txt", "a") as f:
    f.write("New line\n")

# Write multiple lines
with open("output.txt", "w") as f:
    f.writelines(["line 1\n", "line 2\n", "line 3\n"])

CSV (Ch. 10, 21)

import csv

# Read CSV
with open("data.csv", "r", newline="") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["name"], row["score"])

# Write CSV
with open("output.csv", "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "score"])
    writer.writeheader()
    writer.writerow({"name": "Alice", "score": 92})

JSON (Ch. 10, 21)

import json

# Read JSON
with open("data.json", "r") as f:
    data = json.load(f)

# Write JSON
with open("output.json", "w") as f:
    json.dump(data, f, indent=2)

# Convert strings
json_string = json.dumps(data)
data = json.loads(json_string)

pathlib (Ch. 10)

from pathlib import Path

p = Path("data") / "reports" / "summary.txt"
p.exists()          # True / False
p.is_file()         # True / False
p.is_dir()          # True / False
p.name              # "summary.txt"
p.stem              # "summary"
p.suffix            # ".txt"
p.parent            # Path("data/reports")
p.read_text()       # read entire file as string
p.write_text("hi")  # write string to file
p.mkdir(parents=True, exist_ok=True)   # create directory
list(p.parent.glob("*.csv"))           # list matching files

A.11 Common Built-in Functions

Function Purpose Example
print() Display output print("hi", end=" ")
input() Read user input (always returns str) name = input("Name: ")
len() Length of sequence/collection len([1, 2, 3])3
type() Type of an object type(42)<class 'int'>
int() Convert to integer int("42")42
float() Convert to float float("3.14")3.14
str() Convert to string str(42)"42"
bool() Convert to boolean bool(0)False
abs() Absolute value abs(-7)7
round() Round to n decimal places round(3.14159, 2)3.14
min() Minimum value min(3, 1, 4)1
max() Maximum value max(3, 1, 4)4
sum() Sum of iterable sum([1, 2, 3])6
sorted() Return new sorted list sorted([3, 1, 2])[1, 2, 3]
reversed() Return reversed iterator list(reversed([1, 2, 3]))
range() Generate integer sequence range(5)0, 1, 2, 3, 4
enumerate() Index + value pairs list(enumerate(["a","b"]))
zip() Pair up elements list(zip([1,2], ["a","b"]))
map() Apply function to each element list(map(int, ["1","2"]))
filter() Keep elements passing test list(filter(bool, [0,1,2]))
any() True if any element is truthy any([False, True])True
all() True if all elements are truthy all([True, True])True
isinstance() Type check isinstance(42, int)True
id() Memory address of object id(x)
hash() Hash value hash("hello")
ord() Character to Unicode code point ord("A")65
chr() Code point to character chr(65)"A"
help() Interactive help help(str.split)
dir() List attributes dir(str)
open() Open a file See A.10

A.12 f-String Formatting (Ch. 3, 7)

Basic Insertion

name = "Alice"
age = 30
print(f"Name: {name}, Age: {age}")

Format Specifications

Spec Meaning Example Result
:.2f 2 decimal places f"{3.14159:.2f}" "3.14"
:.0f No decimals f"{3.7:.0f}" "4"
:, Thousands separator f"{1000000:,}" "1,000,000"
:>10 Right-align, width 10 f"{'hi':>10}" " hi"
:<10 Left-align, width 10 f"{'hi':<10}" "hi "
:^10 Center, width 10 f"{'hi':^10}" " hi "
:05d Zero-pad integer f"{42:05d}" "00042"
:% Percentage f"{0.85:%}" "85.000000%"
:.1% Percentage, 1 decimal f"{0.85:.1%}" "85.0%"

Expressions Inside f-Strings

f"{2 + 3}"                    # "5"
f"{name.upper()}"             # "ALICE"
f"{'even' if x % 2 == 0 else 'odd'}"
f"{price:.2f}"                # "19.99"

A.13 Error Handling (Ch. 11)

try:
    result = risky_operation()
except ValueError as e:
    print(f"Bad value: {e}")
except (TypeError, KeyError):
    print("Type or key problem")
except Exception as e:
    print(f"Unexpected: {e}")
else:
    print("No error occurred")
finally:
    print("Always runs — cleanup here")

Raising Exceptions

raise ValueError("Score must be between 0 and 100")

# Custom exception
class InsufficientFundsError(Exception):
    pass

Common Exception Types

Exception When It Occurs
SyntaxError Invalid Python syntax (caught at parse time)
TypeError Wrong type for an operation
ValueError Right type, wrong value
NameError Undefined variable
IndexError List index out of range
KeyError Dict key not found
AttributeError Object doesn't have that attribute
FileNotFoundError File doesn't exist
ZeroDivisionError Division by zero
ImportError Module not found
RecursionError Maximum recursion depth exceeded
StopIteration Iterator is exhausted

A.14 Common Patterns

Accumulator Pattern (Ch. 5)

# Numeric accumulator
total = 0
for num in numbers:
    total += num

# String accumulator
result = ""
for char in text:
    if char.isalpha():
        result += char

# List accumulator
evens = []
for n in range(20):
    if n % 2 == 0:
        evens.append(n)

Sentinel Loop (Ch. 5)

while True:
    value = input("Enter value (or 'quit'): ")
    if value == "quit":
        break
    process(value)

Swap Pattern (Ch. 3)

a, b = b, a     # Pythonic swap — no temp variable needed

Frequency Counting (Ch. 9)

counts = {}
for item in data:
    counts[item] = counts.get(item, 0) + 1

# Or using defaultdict
from collections import defaultdict
counts = defaultdict(int)
for item in data:
    counts[item] += 1

# Or using Counter
from collections import Counter
counts = Counter(data)

Max/Min Tracking (Ch. 5)

best = numbers[0]
for num in numbers[1:]:
    if num > best:
        best = num

Guard Clause / Early Return (Ch. 6)

def process(value):
    if value is None:
        return
    if value < 0:
        raise ValueError("Must be non-negative")
    # main logic here

Input Validation Loop (Ch. 5)

while True:
    try:
        age = int(input("Enter your age: "))
        if 0 <= age <= 150:
            break
        print("Age must be between 0 and 150.")
    except ValueError:
        print("Please enter a valid integer.")

Read-Process-Write Pipeline (Ch. 10)

with open("input.csv", "r", newline="") as infile:
    reader = csv.DictReader(infile)
    results = []
    for row in reader:
        processed = transform(row)
        results.append(processed)

with open("output.csv", "w", newline="") as outfile:
    writer = csv.DictWriter(outfile, fieldnames=results[0].keys())
    writer.writeheader()
    writer.writerows(results)

A.15 Imports and Modules (Ch. 12)

import math                       # import entire module
from math import sqrt, pi         # import specific names
from collections import Counter   # from standard library
import datetime as dt             # alias

# Conditional main block
if __name__ == "__main__":
    main()

Frequently Used Standard Library Modules

Module Purpose Key Functions/Classes
math Math functions sqrt, pi, ceil, floor, log
random Random numbers randint, choice, shuffle, random
datetime Dates and times datetime.now(), timedelta
os OS interaction os.getcwd(), os.listdir()
sys System info sys.argv, sys.exit()
pathlib File paths Path, see A.10
json JSON data load, dump, loads, dumps
csv CSV data reader, writer, DictReader, DictWriter
collections Specialized containers Counter, defaultdict, deque, namedtuple
itertools Iterator tools chain, product, combinations, permutations
re Regular expressions search, match, findall, sub
unittest Testing framework TestCase, assertEqual
copy Object copying copy, deepcopy

A.16 Testing (Ch. 13)

pytest Style

# test_calculator.py
from calculator import add, divide

def test_add_positive():
    assert add(2, 3) == 5

def test_add_negative():
    assert add(-1, -1) == -2

def test_divide_by_zero():
    import pytest
    with pytest.raises(ZeroDivisionError):
        divide(10, 0)

Run: python -m pytest test_calculator.py -v

Assertions

assert condition, "Error message if assertion fails"
assert len(items) > 0, "List must not be empty"

A.17 Regular Expressions Quick Reference (Ch. 22)

Pattern Matches
. Any character except newline
\d Any digit (0-9)
\w Any word character (letter, digit, underscore)
\s Any whitespace
\D, \W, \S Negations of above
^ Start of string
$ End of string
* Zero or more
+ One or more
? Zero or one
{n} Exactly n times
{n,m} Between n and m times
[abc] Character class — a, b, or c
[^abc] Negated class — not a, b, or c
(...) Capture group
\| Alternation (or)
import re
re.search(r"\d+", "Age: 25")         # Match object
re.findall(r"\b\w+\b", text)         # List of all words
re.sub(r"\s+", " ", text)            # Replace whitespace
re.split(r"[,;]\s*", "a, b; c")     # Split on delimiters

A.18 Git Quick Reference (Ch. 25)

git init                          # Initialize a repository
git status                        # Check current status
git add filename                  # Stage a file
git add .                         # Stage all changes
git commit -m "message"           # Commit staged changes
git log --oneline                 # View commit history
git branch feature-name           # Create a branch
git checkout feature-name         # Switch to a branch
git checkout -b feature-name      # Create and switch
git merge feature-name            # Merge branch into current
git remote add origin URL         # Add remote
git push -u origin main           # Push to remote
git pull                          # Pull from remote
git clone URL                     # Clone a repository
git diff                          # Show unstaged changes

This reference covers Python 3.12+. For the complete language reference, see docs.python.org.