Appendix A: Python Language Quick Reference

Python for Business for Beginners: Coding for Every Person

This appendix is a reference card, not a tutorial. It assumes you have already learned the concepts in the main chapters and want a quick lookup. Code examples use Python 3.10+.


Data Types and Literals

# Integers
count = 42
large = 1_000_000      # underscore separator for readability

# Floats
price = 19.99
rate = 0.085

# Strings
name = "Acme Corp"
multi = """Multiple
lines"""
raw = r"C:\Users\data"  # raw string — backslashes not escaped

# Booleans
is_active = True
has_discount = False

# None
result = None           # represents "no value"

# Complex (rarely needed in business work)
z = 3 + 4j

# Type checking
type(price)             # <class 'float'>
isinstance(count, int)  # True

Type Conversion

int("42")               # 42
int(3.9)                # 3  (truncates, does not round)
float("19.99")          # 19.99
float(42)               # 42.0
str(1000)               # "1000"
str(3.14)               # "3.14"
bool(0)                 # False
bool("")                # False  (empty string is falsy)
bool(1)                 # True
bool("anything")        # True   (non-empty string is truthy)
list("abc")             # ['a', 'b', 'c']
tuple([1, 2, 3])        # (1, 2, 3)
set([1, 2, 2, 3])       # {1, 2, 3}

Operators

Arithmetic

5 + 3          # 8    addition
10 - 4         # 6    subtraction
3 * 7          # 21   multiplication
10 / 3         # 3.333...  true division (always returns float)
10 // 3        # 3    floor division (integer result)
10 % 3         # 1    modulo (remainder)
2 ** 8         # 256  exponentiation

Comparison

x == y         # equal to
x != y         # not equal to
x > y          # greater than
x >= y         # greater than or equal
x < y          # less than
x <= y         # less than or equal

Logical

True and False    # False
True or False     # True
not True          # False

# Short-circuit evaluation
# 'and' returns first falsy value, or last value
0 and "hello"     # 0    (returns 0 because it's falsy)
1 and "hello"     # "hello"

# 'or' returns first truthy value, or last value
0 or "hello"      # "hello"
1 or "hello"      # 1

# Common pattern: default value
name = user_input or "Unknown"

Membership

"apple" in ["apple", "banana"]     # True
"cherry" not in ["apple", "banana"] # True
"key" in {"key": "value"}          # True (checks keys)

Identity

x is None         # True if x is the None object
x is not None     # True if x is not None
# Use 'is' for None, True, False comparisons
# Use '==' for value comparisons

Assignment Operators

x += 5    # same as: x = x + 5
x -= 3
x *= 2
x /= 4
x //= 2
x **= 3
x %= 7

String Methods (Most Useful 20)

s = "  Hello, Business World!  "

# Case
s.lower()              # "  hello, business world!  "
s.upper()              # "  HELLO, BUSINESS WORLD!  "
s.title()              # "  Hello, Business World!  "

# Whitespace
s.strip()              # "Hello, Business World!"
s.lstrip()             # "Hello, Business World!  "
s.rstrip()             # "  Hello, Business World!"

# Search
s.find("Business")     # 9   (index of first occurrence, -1 if not found)
s.count("l")           # 3
s.startswith("  H")    # True
s.endswith("!  ")      # True
"abc" in s             # False (membership)

# Replace and split
s.replace("World", "Python")   # "  Hello, Business Python!  "
"a,b,c".split(",")              # ['a', 'b', 'c']
",".join(["a", "b", "c"])       # "a,b,c"

# Test content
"abc123".isdigit()     # False
"12345".isdigit()      # True
"hello".isalpha()      # True
"hello world".isalpha() # False (space is not alpha)

# Padding and alignment
"42".zfill(5)          # "00042"
"hi".ljust(10)         # "hi        "
"hi".rjust(10)         # "        hi"
"hi".center(10)        # "    hi    "

f-strings (Preferred Formatting)

name = "Acme"
revenue = 1234567.89
rate = 0.0856

f"Company: {name}"                     # "Company: Acme"
f"Revenue: ${revenue:,.2f}"            # "Revenue: $1,234,567.89"
f"Growth rate: {rate:.1%}"             # "Growth rate: 8.6%"
f"{'Label':>15}: {42:<10}"            # padded alignment
f"{name!r}"                            # repr: "'Acme'"
f"{name!u}"                            # INVALID — use name.upper()

# Multiline f-string
report = (
    f"Company: {name}\n"
    f"Revenue: ${revenue:,.2f}\n"
    f"Rate: {rate:.2%}"
)

List Methods

items = [3, 1, 4, 1, 5, 9, 2, 6]

# Adding
items.append(7)         # add to end: [3, 1, 4, 1, 5, 9, 2, 6, 7]
items.insert(0, 0)      # insert at index: [0, 3, 1, ...]
items.extend([8, 9])    # add multiple items

# Removing
items.remove(1)         # remove first occurrence of value 1
popped = items.pop()    # remove and return last item
popped = items.pop(0)   # remove and return item at index 0
items.clear()           # remove all items

# Searching
items.index(5)          # index of value 5 (raises ValueError if not found)
items.count(1)          # count of value 1

# Sorting
items.sort()                    # sort in place, ascending
items.sort(reverse=True)        # sort descending
items.sort(key=lambda x: -x)   # sort by custom key
sorted_copy = sorted(items)     # returns new sorted list

# Other
items.reverse()         # reverse in place
copy = items.copy()     # shallow copy
length = len(items)     # number of items

# Slicing
items[0]        # first item
items[-1]       # last item
items[1:4]      # items at indices 1, 2, 3
items[:3]       # first three
items[3:]       # from index 3 to end
items[::2]      # every other item
items[::-1]     # reversed copy

Dictionary Methods

prices = {"apple": 1.20, "banana": 0.50, "cherry": 3.00}

# Access
prices["apple"]                  # 1.20 (KeyError if missing)
prices.get("grape")              # None (no error)
prices.get("grape", 0.0)         # 0.0 (default value)

# Modify
prices["grape"] = 2.50          # add or update
prices.update({"kiwi": 1.80})   # add/update multiple
del prices["banana"]            # remove key (KeyError if missing)
removed = prices.pop("cherry")  # remove and return value
prices.pop("missing", None)     # safe pop with default

# Iteration
prices.keys()           # dict_keys(['apple', 'grape', 'kiwi'])
prices.values()         # dict_values([1.20, 2.50, 1.80])
prices.items()          # dict_items([('apple', 1.20), ...])

for key, value in prices.items():
    print(f"{key}: ${value:.2f}")

# Check membership
"apple" in prices       # True (checks keys)

# Other
len(prices)             # 3
prices.copy()           # shallow copy
prices.clear()          # remove all items

# Merge (Python 3.9+)
combined = prices | {"mango": 4.00}    # new merged dict
prices |= {"mango": 4.00}              # update in place

Set Operations

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

a | b           # union: {1, 2, 3, 4, 5, 6}
a & b           # intersection: {3, 4}
a - b           # difference (in a, not in b): {1, 2}
a ^ b           # symmetric difference (in one but not both): {1, 2, 5, 6}

a.add(7)
a.remove(1)     # KeyError if not present
a.discard(99)   # no error if not present
a.pop()         # remove and return an arbitrary element

# Comparisons
{1, 2} <= {1, 2, 3}    # True  (subset)
{1, 2, 3} >= {1, 2}    # True  (superset)

Control Flow

if/elif/else

score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

# Ternary (one-liner if/else)
status = "pass" if score >= 70 else "fail"

# Truthy/falsy shortcuts
# These are all falsy: None, 0, 0.0, "", [], {}, set()
if not items:    # True when items is empty list
    print("No items")

for loops

# Iterating a list
for item in ["a", "b", "c"]:
    print(item)

# With index
for i, item in enumerate(["a", "b", "c"]):
    print(f"{i}: {item}")      # 0: a, 1: b, 2: c

# Range
for i in range(5):             # 0, 1, 2, 3, 4
    pass
for i in range(1, 6):          # 1, 2, 3, 4, 5
    pass
for i in range(0, 10, 2):      # 0, 2, 4, 6, 8
    pass

# Iterating a dictionary
for key in d:
    pass
for key, value in d.items():
    pass

# Iterating two lists together
for name, score in zip(names, scores):
    print(f"{name}: {score}")

# break and continue
for item in items:
    if item == "skip":
        continue    # skip this iteration
    if item == "stop":
        break       # exit loop entirely

# else on for loop (runs if loop completed without break)
for item in items:
    if item == "target":
        break
else:
    print("target not found")

while loops

count = 0
while count < 10:
    count += 1

# With break
while True:
    response = input("Continue? (y/n): ")
    if response.lower() == "n":
        break

Functions

# Basic function with type hints and docstring
def calculate_margin(
    revenue: float,
    cost: float,
) -> float:
    """Calculate gross margin percentage.

    Args:
        revenue: Total revenue in dollars.
        cost: Total cost of goods sold in dollars.

    Returns:
        Gross margin as a decimal (e.g., 0.35 for 35%).

    Raises:
        ValueError: If revenue is zero or negative.
    """
    if revenue <= 0:
        raise ValueError(f"Revenue must be positive, got {revenue}")
    return (revenue - cost) / revenue


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

greet("Priya")              # "Hello, Priya!"
greet("Priya", "Good morning")  # "Good morning, Priya!"


# *args: accept any number of positional arguments
def total(*amounts: float) -> float:
    return sum(amounts)

total(10, 20, 30)    # 60.0


# **kwargs: accept any number of keyword arguments
def build_report(**fields: str) -> str:
    return "\n".join(f"{k}: {v}" for k, v in fields.items())

build_report(name="Acme", quarter="Q3", status="approved")


# Returning multiple values (as a tuple)
def min_max(values: list[float]) -> tuple[float, float]:
    return min(values), max(values)

low, high = min_max([3, 1, 4, 1, 5, 9])


# Lambda (anonymous function)
square = lambda x: x ** 2
square(5)    # 25

# Common lambda use with sorted/map/filter
items.sort(key=lambda x: x["revenue"])
filtered = list(filter(lambda x: x > 0, values))
doubled = list(map(lambda x: x * 2, values))

Exception Handling

# Basic try/except
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

# Multiple exception types
try:
    value = int(user_input)
    result = items[value]
except ValueError:
    print("Please enter a number")
except IndexError:
    print("Number out of range")
except Exception as e:
    print(f"Unexpected error: {e}")

# try/except/else/finally
try:
    file = open("data.csv")
except FileNotFoundError:
    print("File not found")
else:
    # Runs only if no exception occurred
    data = file.read()
finally:
    # Always runs — good for cleanup
    file.close()

# Preferred pattern: context manager (handles close automatically)
try:
    with open("data.csv", encoding="utf-8") as f:
        data = f.read()
except FileNotFoundError as e:
    print(f"File not found: {e}")

# Raising exceptions
def validate_positive(value: float, name: str = "value") -> None:
    if value <= 0:
        raise ValueError(f"{name} must be positive, got {value}")

# Common exception types:
# ValueError       — wrong value (negative where positive expected)
# TypeError        — wrong type (string where number expected)
# KeyError         — dictionary key not found
# IndexError       — list index out of range
# FileNotFoundError — file does not exist
# ZeroDivisionError — division by zero
# AttributeError   — object has no such attribute
# ImportError      — module not found
# RuntimeError     — general runtime error

File I/O

from pathlib import Path

# Reading a text file
with open("notes.txt", encoding="utf-8") as f:
    content = f.read()          # entire file as one string

with open("notes.txt", encoding="utf-8") as f:
    lines = f.readlines()       # list of lines (includes \n)

with open("notes.txt", encoding="utf-8") as f:
    for line in f:              # most memory-efficient for large files
        process(line.strip())

# Writing a text file
with open("output.txt", "w", encoding="utf-8") as f:
    f.write("First line\n")
    f.write("Second line\n")

# Appending to a file
with open("log.txt", "a", encoding="utf-8") as f:
    f.write("New entry\n")

# CSV reading
import csv

with open("data.csv", encoding="utf-8", newline="") as f:
    reader = csv.DictReader(f)
    rows = list(reader)         # list of dicts

# CSV writing
with open("output.csv", "w", encoding="utf-8", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "amount"])
    writer.writeheader()
    writer.writerow({"name": "Acme", "amount": 1000})

# JSON
import json

# Load from file
with open("config.json", encoding="utf-8") as f:
    config = json.load(f)

# Load from string
data = json.loads('{"key": "value"}')

# Save to file
with open("output.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2)

# Dump to string
json_string = json.dumps(data, indent=2)

# pathlib for file paths
from pathlib import Path

p = Path("data/sales/q3.csv")
p.exists()              # True or False
p.suffix                # ".csv"
p.stem                  # "q3"
p.name                  # "q3.csv"
p.parent                # Path("data/sales")
p.parent.mkdir(parents=True, exist_ok=True)  # create directory

# Safe file reading pattern
def read_csv_safe(file_path: str | Path) -> list[dict]:
    path = Path(file_path)
    if not path.exists():
        raise FileNotFoundError(f"File not found: {path}")
    with open(path, encoding="utf-8", newline="") as f:
        return list(csv.DictReader(f))

Common Standard Library Modules

os and pathlib

import os
from pathlib import Path

os.getcwd()                     # current working directory
os.listdir(".")                 # list files in directory
os.makedirs("new/dir", exist_ok=True)

Path.home()                     # home directory
Path.cwd()                      # current working directory
list(Path(".").glob("*.csv"))   # all CSV files in current dir
list(Path(".").rglob("*.py"))   # all .py files recursively

datetime

from datetime import datetime, date, timedelta

today = date.today()                    # date(2025, 3, 15)
now = datetime.now()                    # datetime(2025, 3, 15, 14, 30, 0)
specific = datetime(2025, 1, 1)

# Formatting
now.strftime("%Y-%m-%d")               # "2025-03-15"
now.strftime("%B %d, %Y")             # "March 15, 2025"
now.strftime("%Y-%m-%d %H:%M:%S")     # "2025-03-15 14:30:00"

# Parsing
datetime.strptime("2025-01-15", "%Y-%m-%d")

# Arithmetic
tomorrow = today + timedelta(days=1)
last_week = today - timedelta(weeks=1)
diff = datetime(2025, 12, 31) - datetime.now()
diff.days                              # days until end of year

collections

from collections import Counter, defaultdict, namedtuple, OrderedDict

# Counter: count occurrences
words = ["apple", "banana", "apple", "cherry", "apple"]
c = Counter(words)
c["apple"]                    # 3
c.most_common(2)              # [('apple', 3), ('banana', 1)]

# defaultdict: dict with default value for missing keys
sales_by_region = defaultdict(float)
sales_by_region["North"] += 1000   # no KeyError for new key

# namedtuple: lightweight immutable record
Product = namedtuple("Product", ["code", "name", "price"])
p = Product("A001", "Widget", 9.99)
p.name          # "Widget"
p.price         # 9.99

itertools

import itertools

# chain: iterate multiple sequences as one
for item in itertools.chain([1, 2], [3, 4], [5]):
    print(item)   # 1, 2, 3, 4, 5

# groupby: group consecutive items by key
# (data must be sorted by key first)
from itertools import groupby

data = [("North", 100), ("North", 200), ("South", 150)]
for region, items in groupby(data, key=lambda x: x[0]):
    print(region, list(items))

# product: Cartesian product
for size, color in itertools.product(["S", "M", "L"], ["red", "blue"]):
    print(size, color)   # S red, S blue, M red, ...

# islice: slice an iterator without materializing it
first_10 = list(itertools.islice(large_generator, 10))

functools

from functools import reduce, partial, lru_cache

# reduce: combine items with a function
from functools import reduce
total = reduce(lambda x, y: x + y, [1, 2, 3, 4])   # 10

# partial: fix some arguments of a function
from functools import partial
double = partial(lambda x, y: x * y, 2)
double(5)    # 10

# lru_cache: cache expensive function results
@lru_cache(maxsize=128)
def expensive_calculation(n: int) -> int:
    return n ** 2

Comprehensions

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# List comprehension
squares = [n ** 2 for n in numbers]
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# With condition
even_squares = [n ** 2 for n in numbers if n % 2 == 0]
# [4, 16, 36, 64, 100]

# Dict comprehension
square_dict = {n: n ** 2 for n in numbers}
# {1: 1, 2: 4, 3: 9, ...}

# Filtered dict comprehension
large_squares = {n: n ** 2 for n in numbers if n > 5}
# {6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

# Set comprehension
unique_remainders = {n % 3 for n in numbers}
# {0, 1, 2}

# Generator expression (does not create a list in memory)
total = sum(n ** 2 for n in numbers)   # 385

# Nested comprehension (use sparingly — can be hard to read)
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
# [[1, 2, 3], [2, 4, 6], [3, 6, 9]]

Classes and OOP (Enough to Read Other People's Code)

class Customer:
    """Represents a business customer."""

    # Class variable (shared by all instances)
    customer_count = 0

    def __init__(self, name: str, email: str, tier: str = "standard") -> None:
        """Initialize a Customer.

        Args:
            name: Customer's full name.
            email: Customer's email address.
            tier: Account tier — "standard", "premium", or "enterprise".
        """
        self.name = name          # instance variable
        self.email = email
        self.tier = tier
        Customer.customer_count += 1

    def __repr__(self) -> str:
        """Return unambiguous string representation."""
        return f"Customer(name={self.name!r}, tier={self.tier!r})"

    def __str__(self) -> str:
        """Return human-readable string representation."""
        return f"{self.name} ({self.tier})"

    def get_discount(self) -> float:
        """Return discount rate based on tier."""
        discounts = {"standard": 0.0, "premium": 0.10, "enterprise": 0.20}
        return discounts.get(self.tier, 0.0)


# Creating instances
c = Customer("Acme Corp", "acme@example.com", tier="enterprise")
c.name          # "Acme Corp"
c.get_discount()  # 0.20
str(c)           # "Acme Corp (enterprise)"
repr(c)          # "Customer(name='Acme Corp', tier='enterprise')"


# Inheritance
class PremiumCustomer(Customer):
    """Customer with additional premium features."""

    def __init__(self, name: str, email: str, account_manager: str) -> None:
        super().__init__(name, email, tier="premium")
        self.account_manager = account_manager


# Dataclass (Python 3.7+ — cleaner for simple data containers)
from dataclasses import dataclass, field

@dataclass
class SalesRecord:
    date: str
    region: str
    revenue: float
    cost: float = 0.0
    tags: list[str] = field(default_factory=list)

    @property
    def margin(self) -> float:
        """Gross margin percentage."""
        if self.revenue == 0:
            return 0.0
        return (self.revenue - self.cost) / self.revenue


record = SalesRecord("2025-01-15", "North", 10000, 6500)
record.margin   # 0.35

Type Hints Reference (Python 3.10+)

from typing import Optional
# Python 3.10+ allows X | None instead of Optional[X]

# Basic types
def process(name: str, count: int, rate: float, active: bool) -> None:
    ...

# Optional (can be None)
def find_user(user_id: int) -> str | None:
    ...

# Lists, dicts, sets
def summarize(items: list[float]) -> dict[str, float]:
    ...

# Tuples
def get_bounds(values: list[float]) -> tuple[float, float]:
    ...

# Union types (Python 3.10+)
def process_input(value: int | float | str) -> str:
    ...

# Callable
from collections.abc import Callable
def apply(func: Callable[[float], float], value: float) -> float:
    return func(value)

# Any (escape hatch — avoid when possible)
from typing import Any
def debug_print(value: Any) -> None:
    print(repr(value))

Common Patterns

Context Manager (with statement)

# File handling
with open("file.txt") as f:
    content = f.read()

# Database connection
with sqlite3.connect("db.sqlite") as conn:
    conn.execute("INSERT INTO ...")

# Custom context manager
from contextlib import contextmanager

@contextmanager
def timer(label: str):
    import time
    start = time.time()
    yield
    elapsed = time.time() - start
    print(f"{label}: {elapsed:.3f}s")

with timer("data loading"):
    df = pd.read_csv("large_file.csv")

Environment Variables (for credentials)

import os
from dotenv import load_dotenv  # pip install python-dotenv

load_dotenv()  # loads .env file into environment

api_key = os.getenv("API_KEY")
db_url = os.environ["DATABASE_URL"]  # raises KeyError if missing
port = int(os.getenv("PORT", "8080"))  # with default

Logging

import logging

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s | %(levelname)s | %(message)s",
)
logger = logging.getLogger(__name__)

logger.debug("Detailed debugging info")
logger.info("Normal operation message")
logger.warning("Something unexpected but not fatal")
logger.error("Something failed")
logger.exception("Exception occurred", exc_info=True)

For the full language reference, see docs.python.org/3. For pandas-specific reference, see Appendix B.