PCAP Cheatsheet
Certified Associate in Python Programming
Download free PDFCore language and collections
Execution, names and numbers
- A **compiler** translates source into another representation and can detect syntax errors. **CPython** compiles Python source to bytecode, then executes it with its interpreter; compilation does not prove runtime correctness.
- **Identifiers** are case-sensitive, cannot start with a digit and cannot be reserved keywords such as `for`, `class` or `True`. Assignment binds a name to an object; the name itself has no fixed type.
- **Numeric literals** can use scientific notation: `3.423e1` and `3423e-2` both represent 34.23. An exponent after `e` scales by a power of ten.
- **Arithmetic:** two adjacent asterisks form the exponentiation operator; `/` performs true division; `//` floors the quotient; `%` gives the remainder. For integers, `a == (a // b) * b + a % b` when `b != 0`.
- **Precedence** places exponentiation before multiplication and division, then addition and subtraction. Exponentiation associates right to left and binds before unary negation on its left: negating the square of 2 gives -4; squaring -2 gives 4.
- **Bitwise operators** act on integers: `&`, `|`, `^`, `~`, `<<` and `>>`. Left shift multiplies by a power of two; right shift floors division by that power. Python has no `>>>`, `++` or `--` increment operator.
Conditions, loops and output
- **Truth testing** treats `None`, zero and empty containers as false. `not` returns a Boolean; `and` and `or` short-circuit and return an operand. Comparison operators bind before `not`, then `and`, then `or`.
- **Equality** (`==`) compares values; **identity** (`is`) checks whether two references denote the same object. Use `is None` to test for the singleton `None`.
- **while** tests its condition before each iteration. **for** takes successive items from an iterable; `range(start, stop, step)` excludes `stop`. A zero step is invalid.
- **break** exits the nearest loop; **continue** skips to its next iteration. A loop's `else` runs when the loop finishes without `break`, including when there are no iterations.
- A loop target remains bound after a **for** loop if an iteration assigned it. If there were no iterations, the loop creates no new binding. Loops do not introduce a separate variable scope.
- **print** separates arguments with `sep` and appends `end`; their defaults are a space and a newline. Count emitted newline characters when tracing output, including those inside strings.
Sequences, mutation and mappings
- **Lists** are mutable; **tuples** and **strings** are immutable. All support indexing and slicing. Containers can nest: a tuple may contain a list, and that inner list can still change.
- **Assignment** can create aliases: after `b = a`, mutating a list through either name affects the same object. `a[:]` and `a.copy()` create shallow list copies; nested objects remain shared.
- **Unpacking** evaluates the right-hand side before assigning targets. `a, b = b, a` swaps bindings. A one-item tuple needs a comma, as in `(value,)`.
- **List updates:** `append(x)` adds one item; `extend(items)` adds each item; `insert(i, x)` inserts before an index. A comprehension builds a new list by evaluating its expression for each selected item.
- **Deletion** differs from rebinding: `del items[:]` empties the existing list, preserving aliases; `del items` removes that name. Deleting a tuple name does not mutate the tuple.
- **Dictionaries** map unique hashable keys to values. Assigning an existing key replaces its value. Quoted keys such as `'Mom'` are strings; an unquoted name must already be bound.
- **Membership** in a dictionary tests keys: `key in d` or `key in d.keys()`. `d[key]` raises `KeyError` when absent; `d.get(key)` defaults to `None`, which alone cannot distinguish a missing key from a stored `None`.
Modules and packages
Imports and module names
- A **module** groups definitions in its own namespace. With `import tools`, access a member as `tools.helper()`. With `from tools import helper`, call `helper()` directly.
- **Aliases** use `as`: `import package.module as mod` binds `mod`; `from tools import helper as h` binds `h`. Python has no `alias` keyword, and shortening a dotted path arbitrarily does not resolve it.
- **Imported bindings** follow normal assignment rules. After `from tools import value`, rebinding local `value` does not assign `tools.value`; mutation of a shared mutable object is visible through both references.
- **Wildcard imports** bind exported names in the current namespace; they do not automatically bind the module name. Prefer explicit imports to avoid name collisions.
- **__name__** is the module's import name when imported and `'__main__'` when run as the top-level program. Guard runnable code with `if __name__ == '__main__':`.
- A module's top-level code normally runs on its **first import** in a process. Later imports reuse the cached module from `sys.modules`; importing is not the same as repeatedly calling a function.
Packages and bytecode
- A **package** organizes modules and subpackages under dotted names. `import pkg.sub.mod` supports access through that path; `from pkg.sub import mod` binds `mod` directly.
- A regular package typically has **__init__.py**. Namespace packages can omit it. Imports depend on the module search path, including entries in **sys.path**, rather than just the current file's directory structure.
- **.pyc files** cache compiled bytecode, commonly under `__pycache__`. In `tools.cpython-36.pyc`, `cpython-36` identifies the implementation and interpreter release, not the source revision.
- **ZIP imports** can load Python modules and packages from suitable archives on the search path. A ZIP is a distribution container; it does not make arbitrary native extension modules directly importable.
Platform information and randomness
- **platform.platform()** returns a descriptive platform string. **platform.system()** reports the operating system name; **platform.uname()** returns structured system information.
- **platform.python_version()** describes the Python version. **platform.processor()** reports processor information, which may be empty or platform-dependent.
- **random.random()** returns a floating-point value in `[0.0, 1.0)`. **randint(a, b)** includes both endpoints; **randrange** follows `range` boundaries.
- **random.choice(seq)** selects one item from a nonempty sequence. **random.sample(population, k)** returns a list of `k` selections without replacement; equal population values can still appear more than once.
- A fixed **seed** makes a pseudorandom sequence reproducible under the same generator behavior. Separate guaranteed bounds and result lengths from a particular random outcome.
Strings and text
Unicode, literals and slicing
- **Unicode** assigns code points to characters. **ASCII** covers the first 128 code points; **UTF-8** is an encoding of Unicode, not a synonym for it. Python `str` holds Unicode text; `bytes` holds byte values.
- **ord(c)** returns the code point of a one-character string; **chr(n)** returns the character for a valid code point. Thus `chr(ord(c)) == c`; types and valid ranges still matter.
- **Escapes** begin with a backslash: `\n` is newline, `\t` is tab and `\\` is one backslash. Escaped quotes contribute one character. Triple quotes permit multiline literals; whitespace inside them remains text.
- **Indexing** is zero-based; negative indexes count from the end. A string index returns a one-character string. Out-of-range indexing raises `IndexError`; an out-of-range slice is clipped.
- **Slices** use `s[start:stop:step]`, excluding `stop`. Omitted bounds depend on the step direction; `s[::-1]` reverses the string. A step of zero raises `ValueError`.
- **String operations** return new values because strings are immutable. `+` concatenates, `*` repeats by an integer count, and `in` tests a contiguous, case-sensitive substring. The empty string belongs to every string.
Searching, splitting and comparing
- **find** and **rfind** return the first or last match index, or -1 when absent. **index** and **rindex** instead raise `ValueError` when no match exists. These are string methods, such as `text.find('py')`.
- **split()** separates runs of whitespace and drops leading or trailing empty fields. **split(' ')** uses exactly one space as the separator and preserves empty fields between repeated spaces.
- **join** combines strings using a separator: `' '.join(words)`. **strip** removes edge whitespace by default; with an argument, it removes characters from that set, not one exact substring.
- **lower()** and **upper()** produce case-converted copies; they do not modify the original. **islower()** and **isupper()** require at least one cased character and test all cased characters.
- **String ordering** is lexicographic by Unicode code points, with case significant. Numeric-looking strings are still text: `'10' < '2'`. Equality between a number and a string is false; ordering them raises `TypeError`.
- **Conversions** are explicit: `int('12')`, `float('3.14')` and `str(12)`. Malformed numeric text raises `ValueError`. Concatenating a string and a number with `+` raises `TypeError`.
- **sorted(text)** returns a new list of characters. Strings have no `sort()` method. **list.sort()** mutates a list and returns `None`; **sorted(iterable)** creates a list without changing the input.
Classes and object-oriented programming
Classes, initialization and methods
- A **class** defines a type; calling it creates an **instance**. One class can create many objects with independent state. `class Item: pass` is a valid minimal definition.
- **__init__** initializes an already created instance and must return `None`. It is often called the constructor; **__new__** creates the instance. Returning another value from `__init__` raises `TypeError`.
- An ordinary **instance method** receives the instance as its first parameter when called through an object. The conventional name is **self**, but that spelling is not a language requirement.
- **Bound calls** supply the receiver automatically: `obj.method(x)` corresponds to `Class.method(obj, x)` for that method. Within another method, use `self.method()` or `self.attribute` to access instance members.
- Python does not overload methods by declaring several definitions with different signatures: a later definition with the same name replaces the earlier binding. Use defaults or argument handling for one flexible initializer.
Attributes, sharing and introspection
- **Instance attributes**, commonly assigned through `self`, belong to individual objects. **Class attributes** belong to the class and can be shared; objects of the same class need not have identical instance attributes.
- In ordinary attribute lookup, an instance's own value can **shadow** a class value. Assigning `obj.count = 1` normally creates an instance attribute; assigning `Class.count = 1` changes the class attribute.
- A mutable **class attribute** can be shared unexpectedly: appending to `self.items` may mutate the class list. Create a new list inside `__init__` when each instance needs independent storage.
- **hasattr(obj, 'name')** checks attribute availability; **getattr** retrieves it and can supply a default. **__dict__** exposes directly stored attributes for ordinary objects, rather than all inherited members.
- **Name mangling** changes a class member such as `__value` to a name like `_ClassName__value`. It reduces accidental clashes in subclasses; it is not access control. Special names such as `__init__` are not mangled.
- **Class.__name__** gives its name; **Class.__module__** identifies the defining module. **Class.__bases__** is a tuple of direct base class objects, not their names or all ancestors. **__str__** customizes `str(obj)`.
Inheritance, MRO and polymorphism
- **Inheritance** specializes a base class. A subclass can reuse or override methods. Calls such as `self.action()` resolve against the actual object, allowing an inherited method to invoke a subclass override.
- If a subclass defines **__init__**, base initialization is not automatically added. Use **super().__init__(...)** when needed. If the subclass has no initializer, it can inherit one.
- **super()** follows the method resolution order, which matters in multiple inheritance. Explicit `Base.method(self, ...)` selects that base implementation directly and can bypass cooperative dispatch.
- **MRO** uses C3 linearization to preserve consistent inheritance ordering. Inspect `Class.__mro__` or `Class.mro()`; incompatible base orderings and inheritance cycles prevent class creation.
- **issubclass(Child, Parent)** checks class inheritance and is also true for a class compared with itself. **isinstance(obj, Parent)** accepts instances of the class or its subclasses. Neither is an identity test.
- **Polymorphism** allows different objects to respond to the same method call. **Composition** stores another object as a component; inheriting from a class and holding an instance of it express different relationships.
Exceptions and error handling
Exception flow and matching
- An **exception** interrupts normal execution. Within `try`, statements after the failure are skipped; Python looks for a matching handler, then propagates outward if none matches.
- **except Type as e** binds the caught exception. **except (TypeA, TypeB) as e** handles either type. A handler also catches subclasses; place specific handlers before broad base classes.
- **else** on a `try` statement runs only when the try suite completes without an exception. **finally** runs on exit under normal language control flow, including after a handled error or a pending return.
- **raise ErrorType(message)** signals a failure; bare **raise** reraises the currently handled exception. **assert condition** raises `AssertionError` when false, but assertions may be disabled and should not enforce required input validation.
- **Exception.args** stores constructor arguments; `str(e)` usually gives a readable message. User-defined application exceptions normally inherit from **Exception**.
Common exceptions and OS errors
- **TypeError** signals an unsupported type or call shape; **ValueError** signals an unsuitable value of an otherwise accepted type. **NameError** concerns an unresolved name; **AttributeError** concerns a missing attribute.
- **IndexError** concerns an invalid sequence index; **KeyError** concerns a missing mapping key. Both derive from **LookupError**. **ZeroDivisionError** derives from **ArithmeticError**.
- **OSError** covers many filesystem failures; **FileNotFoundError** is a subclass. Its **errno** attribute can be compared with symbolic constants such as `errno.ENOENT`, avoiding platform-specific numeric assumptions.
- A malformed program can fail with **SyntaxError** before normal execution. Catching **Exception** handles most application errors but excludes direct **BaseException** subclasses such as `KeyboardInterrupt` and `SystemExit`.
Functions and file streams
Function calls and bindings
- **Positional arguments** bind by position; **keyword arguments** bind by parameter name. Ordinary positional arguments precede keywords. Missing required arguments, unknown keywords or multiple values for one parameter raise `TypeError`.
- **Default arguments** fill omitted parameters and are evaluated when the function is defined. A mutable default can retain changes between calls; use a `None` default and create fresh state inside when appropriate.
- **return value** ends the function and supplies a result. Bare `return` and falling off the end return `None`. **pass** does nothing and permits an otherwise empty suite; it does not exit the function.
- Arguments bind local names to the supplied **objects**. Mutating a passed list can affect the caller; rebinding the parameter does not rebind the caller's variable.
- **Functions are objects**: they can be assigned, passed and returned. `b = a` shares the same function object; `a()` invokes it. A function's identity and its return value answer different questions.
- **Scope lookup** normally searches local, enclosing function, global and built-in scopes. Assignment makes a name local unless declared **global** or **nonlocal**; an early read of that uninitialized local raises `UnboundLocalError`.
Lambdas and iterable processing
- A **lambda** contains parameters and one expression: `lambda x, y: pow(x, y)` raises x to the power y. Its expression is returned automatically; a `return` statement is invalid inside the lambda expression.
- **map(function, iterable)** lazily applies a function to items; **filter(predicate, iterable)** lazily retains items whose test is true. Use `list(...)` when a materialized list is needed.
- A **closure** can retain access to an enclosing function's bindings after that function returns. Captured names are resolved when used; a default parameter can capture a value at function creation.
- **yield** produces a generator that suspends and resumes execution. Iterators are consumed as they advance; creating a generator does not immediately execute its whole body.
Opening files and reading text
- **open(path)** defaults to read text mode and returns a stream object; failure raises an exception. **with open(...) as stream** closes the stream when the block exits, including after an exception.
- **Modes:** `r` requires an existing file; `w` creates or truncates; `a` creates or appends; `x` creates exclusively and fails if the file exists. `+` adds reading and writing; `b` selects binary mode.
- **Text streams** read and write `str`, using an encoding. Set `encoding='utf-8'` when that is the file's format. Default text newline handling translates common line endings to `\n` on input.
- **read(1)** reads at most one character in text mode; **read()** reads the remaining content. **readline()** reads one line and normally retains its newline. **readlines()** returns a list of remaining lines.
- **File iteration** yields successive lines. At end of file, text `read` and `readline` return `''`; a blank line is usually `'\n'`. A final line can contain text without a trailing newline.
- **write(text)** writes the supplied text without adding a newline and returns the character count. Add `\n` explicitly for a line ending. **sys.stdin**, **sys.stdout** and **sys.stderr** are the standard streams.
Binary streams and file position
- **Binary mode** transfers bytes without text decoding or newline translation. `stream.read(16)` returns up to 16 bytes; at end of file it returns `b''`. Reads may return fewer bytes than requested.
- **bytearray(16)** creates a writable buffer of 16 zero bytes. **readinto(buffer)** fills available buffer space and returns the number of bytes read; only that prefix is newly read data.
- **bytearray(stream.read(16))** creates a mutable buffer from the bytes actually returned. A **bytes** object is immutable; individual elements of either representation are integers from 0 through 255.
- A stream has a **current position**: successive reads continue from it. **seek** changes position and **tell** reports it; text streams restrict valid seeks because encoded characters need not have a fixed byte length.