StudyToCert

All certifications / PCAP / Cheat sheet

PCAP PCAP-31-03 cheat sheet

Every exam tip and key term from the free PCAP lessons, by domain. Use your browser's Print to save it as a PDF.

Domain 1: Modules and Packages (12%)

Exam tips

Key terms

Namespace
A mapping from names to objects; each module, function call and class has its own.
Alias
An alternative name given with as, for example import math as m, which binds only m.
__all__
A list of strings in a module naming what from module import * should import.
Qualified name
A name written with its module prefix, such as math.sqrt.
Package
A directory of modules (and possibly subpackages) that Python can import by name.
Subpackage
A package nested inside another package, reached with a dot, such as extra.good.
Fully qualified name
The complete dotted path from the top package to an object, such as extra.good.best.sigma.funS.
dir()
Built-in that returns a sorted list of attribute names for an object, or of the current scope when called without arguments.
Dunder name
A name with double underscores on both sides, such as __name__, used for special attributes.
Local scope
The set of names defined in the currently executing block; dir() with no argument lists it.
sys.path
A list of directory strings that Python searches, in order, when importing a module.
PYTHONPATH
An environment variable whose directories are added to sys.path at startup.
Shadowing
When a module earlier on the search path hides a same-named module later on it.
site-packages
The directory where third-party packages installed with pip usually live.
floor()
Rounds down toward negative infinity and returns an int.
ceil()
Rounds up toward positive infinity and returns an int.
trunc()
Discards the fractional part, moving toward zero, and returns an int.
hypot()
Returns the Euclidean distance sqrt(x*x + y*y) as a float.
Pseudo-random
Produced by a deterministic algorithm that only looks random; the same seed gives the same sequence.
Seed
The starting value for the generator; setting it makes results reproducible.
Sampling without replacement
Choosing items so that no position is picked twice, as random.sample() does.
system()
Returns the OS name such as Linux, Windows or Darwin.
machine()
Returns the hardware architecture name such as x86_64 or arm64.
python_implementation()
Returns the interpreter implementation name, for example CPython or PyPy.
python_version_tuple()
Returns (major, minor, patch) as a tuple of strings.
__name__
A module variable holding the module's name, or '__main__' when the file is run directly.
'__main__'
The value of __name__ in the module that started the program.
Top-level code
Statements at module level, outside functions and classes, which run whenever the module is loaded.
Bytecode
The compiled, platform-independent instructions the Python virtual machine executes.
.pyc file
A file containing cached bytecode for an imported module.
__pycache__
The directory where CPython stores .pyc files, beside the source modules.
__init__.py
A file that marks a directory as a regular package and runs when the package is first imported.
Nested package
A package directory placed inside another package directory.
_name convention
A leading underscore marks a module name as internal; from module import * skips it.

Domain 2: Exceptions (14%)

Exam tips

Key terms

Exception
An object representing an error or unusual event that interrupts normal flow.
except branch
A handler that runs when the raised exception matches its class or a subclass of it.
Propagation
An unhandled exception moving outward to enclosing try statements and calling functions.
Bare except
An except with no class, catching everything; it must be the last branch.
Exception tuple
A parenthesized list of classes in one except clause; the branch matches any of them.
as binding
The except ... as name form that gives the handler access to the exception object.
Subclass matching
An except branch also catches instances of subclasses of the listed classes.
Exception instance
The object created when an exception is raised; except ... as name binds it.
args
A tuple holding the arguments passed to the exception's constructor.
str(e)
The printable message of an exception, derived from args.
else branch
Runs only when the try block completes without raising an exception.
finally branch
Runs every time the try statement is left, whether normally, by exception or by return.
Clean-up code
Statements that release resources and therefore belong in finally or a with statement.
BaseException
The root of all built-in exceptions, including non-error signals like KeyboardInterrupt.
ArithmeticError
Parent of ZeroDivisionError, OverflowError and FloatingPointError.
LookupError
Parent of IndexError and KeyError, raised when a key or index is invalid.
raise
Statement that signals an exception, given a class or an instance.
Bare raise
raise with no operand inside an except branch; re-raises the current exception unchanged.
Exception chaining
Linking a new exception to the one that caused it, automatically or with raise ... from.
assert
Statement that raises AssertionError when its condition is false.
AssertionError
The exception raised by a failed assert; a subclass of Exception.
-O option
Interpreter flag that strips assert statements so they are never evaluated.
KeyboardInterrupt
Raised when the user presses the interrupt key (Ctrl+C); inherits directly from BaseException.
SystemExit
Raised by sys.exit(); its code attribute holds the exit status.
except Exception
A broad handler for ordinary errors that deliberately excludes exit and interrupt signals.
Custom exception
A user-defined class inheriting from Exception, raised and caught like built-ins.
Exception hierarchy
A set of related exception classes where a base class lets callers catch the whole group.
super().__init__()
Call to the parent constructor, which sets args and the printed message.

Domain 3: Strings (18%)

Exam tips

Key terms

ASCII
A 7-bit character set of 128 characters numbered 0 to 127.
Unicode
A standard assigning a unique code point to every character in every writing system.
Code point
The number Unicode assigns to a character, written like U+0041.
UTF-8
A variable-length Unicode encoding using 1 to 4 bytes per code point, compatible with ASCII.
ord()
Returns the integer code point of a single-character string.
chr()
Returns the one-character string for an integer code point.
Caesar cipher
A simple substitution that shifts each letter a fixed number of places, easily built with ord and chr.
String literal
Text written in source code between single, double or triple quotes.
Escape sequence
A backslash followed by characters that represent one special character, such as \n.
Raw string
A literal with an r prefix in which backslashes are not treated as escapes.
Index
The position of an element in a sequence, starting at 0.
Negative index
A position counted from the end, where -1 is the last element.
Slice
A subsequence selected with [start:stop:step], excluding the stop position.
Step
The stride between selected positions in a slice; negative values go backwards.
Immutable
Cannot be changed after creation; strings, tuples and bytes are immutable.
Rebinding
Pointing an existing name at a new object, as in s = s.upper().
Hashable
Having a fixed hash value, which immutability makes possible and dictionaries require for keys.
Iteration
Visiting each element of a sequence in turn, as a for loop does with a string's characters.
Membership operator
in or not in, which test whether a value occurs in a container or a substring occurs in a string.
enumerate()
Built-in that pairs each element with its index during iteration.
Concatenation
Joining strings end to end with +.
Replication
Repeating a string a whole number of times with *.
Lexicographic order
Comparing sequences element by element, the first difference deciding the result.
isdigit()
True if the string is non-empty and every character is a digit.
isalnum()
True if the string is non-empty and every character is a letter or digit.
isspace()
True if the string is non-empty and every character is whitespace.
Cased character
A letter with distinct upper and lower forms; isupper() and islower() consider only these.
split()
Returns a list of substrings separated by whitespace or by a given separator.
join()
Called on a separator string; concatenates an iterable of strings with that separator between them.
find() / rfind()
Return the lowest or highest index of a substring, or -1 if it is absent.
index()
Like find() but raises ValueError when the substring is absent.
sorted()
Built-in that returns a new sorted list from any iterable.
list.sort()
Method that sorts a list in place and returns None.
key function
A function passed as key= that computes the value used for comparisons.
Stable sort
A sort that keeps equal items in their original relative order.

Domain 4: Object-Oriented Programming (34%)

Exam tips

Key terms

Class
A blueprint defining the attributes and methods its objects will have.
Object (instance)
A concrete value created from a class, with its own state.
Encapsulation
Bundling data with the methods that manage it and restricting direct access to that data.
Superclass / subclass
A parent class and a class that inherits from it, specializing or extending it.
Instance variable
An attribute stored on one object, usually set as self.name in __init__.
Class variable
An attribute defined in the class body and shared by all instances.
Shadowing
An instance attribute with the same name hiding a class attribute when accessed through that instance.
__dict__
The dictionary (or mapping proxy for classes) holding an object's own attributes.
mappingproxy
The read-only mapping type used for a class's __dict__.
vars()
Built-in returning an object's __dict__.
Private attribute
An attribute whose name starts with two underscores (and does not end with two), subject to name mangling.
Name mangling
Rewriting __name inside a class to _ClassName__name to avoid clashes.
Single-underscore convention
A leading _ marks a name as internal but has no enforcement.
self
The conventional name of a method's first parameter, which receives the instance.
__init__
The initializer that runs automatically when an object is created, setting its attributes.
Default argument
A parameter value used when the caller does not supply one.
Introspection
Examining an object's type and attributes at run time.
hasattr()
Returns True if an object has, or can reach, an attribute with the given string name.
__bases__
A tuple of a class's direct superclasses, available on classes only.
__module__
The name of the module in which a class was defined.
Single inheritance
A class with exactly one direct superclass.
Multiple inheritance
A class that lists two or more direct superclasses.
Overriding
Defining a method in a subclass with the same name as one in a superclass, replacing it for the subclass.
super()
Returns a proxy that finds the next class's version of a method in the method resolution order.
MRO
Method resolution order: the ordered list of classes searched for attributes.
Diamond problem
A hierarchy where two parents share a common ancestor, raising the question of search order.
C3 linearization
The algorithm Python uses to compute a consistent MRO.
__mro__
A class attribute holding its MRO as a tuple of classes.
isinstance()
Returns True if an object is an instance of a class or any of its subclasses.
issubclass()
Returns True if a class is the same as, or derives from, another class.
Identity (is)
Whether two references point to the same object.
Equality (==)
Whether two objects have equal values according to their type.
Polymorphism
The ability of different classes to respond to the same method call in their own way.
Duck typing
Using any object that provides the needed methods, regardless of its class.
__str__()
Special method returning an object's readable string form, used by print() and str().

Domain 5: Miscellaneous (22%)

Exam tips

Key terms

List comprehension
An expression in brackets that builds a list by looping over an iterable.
Filter clause
A trailing if in a comprehension that includes only items meeting a condition.
Conditional expression
A if condition else B, which chooses a value for every item.
Nested comprehension
A comprehension inside another, used to build lists of lists.
Lambda
An anonymous function defined by a single expression whose value it returns.
Higher-order function
A function that takes another function as an argument or returns one.
key function
A function passed to sorted(), min() or max() to compute the comparison value for each item.
map()
Returns an iterator applying a function to each item of one or more iterables.
filter()
Returns an iterator yielding the items for which a function returns a true value.
Iterator
An object producing values one at a time with next(); once exhausted it yields nothing more.
Lazy evaluation
Computing values only when they are requested.
Closure
An inner function that retains access to variables from the enclosing function's scope after it returns.
Enclosing scope
The local scope of an outer function, visible to functions nested inside it.
nonlocal
Declaration that lets an inner function rebind a variable of the enclosing function.
Late binding
Looking up a closure's free variables when it is called, not when it is created.
Generator function
A function containing yield; calling it returns a generator object.
yield
Produces a value and pauses the generator, preserving its state until the next request.
next()
Built-in that asks an iterator for its next value.
StopIteration
Exception raised when an iterator has no more values; for loops handle it automatically.
'w' mode
Write mode: creates the file or truncates an existing one to zero length.
'x' mode
Exclusive creation: creates a new file and fails with FileExistsError if it exists.
Text mode
Mode that decodes bytes to str using an encoding and translates line endings.
Binary mode
Mode ('b') that reads and writes raw bytes with no decoding or translation.
Stream
An ordered flow of data that a program reads from or writes to.
Stream handle
The object returned by open() (or provided by sys) through which a stream is used.
sys.stdout
Standard output, the default destination of print().
sys.stderr
Standard error, a separate output stream for error messages and diagnostics.
readline()
Reads one line including its newline; returns an empty string at end of file.
readlines()
Returns a list of all remaining lines, each keeping its newline.
readinto()
Fills an existing bytearray from a binary file and returns the number of bytes read.
with statement
A context manager block that closes the file automatically when it ends.
errno attribute
The operating system error code stored on an OSError instance.
errno module
Standard module defining named constants such as ENOENT and EACCES for error codes.
ENOENT
Error code meaning no such file or directory; matches FileNotFoundError.
EACCES
Error code meaning permission denied; matches PermissionError.
Study PCAP for free
Lessons, quizzes, exam simulations and hands-on labs.
Open the PCAP study plan