All certifications / PCAP / Cheat sheet
PCAP PCAP-31-03 cheat sheet
Domain 1: Modules and Packages (12%)
Exam tips
- Ask which names each line adds. import m as x defines only x, never m; from m import f defines only f, never m. Many answer options that look fine fail with NameError for exactly this reason.
- With plain import a.b.c you must use the full a.b.c prefix, and the last component must be a module, not a function or class. Questions often offer import a.b.func as a tempting wrong answer.
- dir(x) needs a name that actually exists. After from math import sqrt, dir(math) raises NameError; after import math as m, you must call dir(m).
- append() searches the new folder last, insert(0, ...) searches it first, and neither change survives past the current run. The modification must come before the import that relies on it.
- Test negatives: floor(-2.5) is -3 but trunc(-2.5) and ceil(-2.5) are -2. Also remember sqrt and hypot always return floats, so sqrt(16) prints 4.0, not 4.
- random() can return 0.0 but never 1.0, and sample() raises ValueError if k exceeds the population size. Same seed plus same calls equals same output.
- platform.version() is the operating system's version, not Python's. python_version_tuple() returns strings, not integers, and processor() may legitimately return an empty string.
- Imports still run all unguarded top-level code. Only statements inside the if __name__ == '__main__': block are skipped when the file is imported.
- The main script is compiled but not cached; only imported modules get .pyc files. Caching speeds up loading, not execution.
- A leading underscore only affects from module import *. Explicit imports and qualified access such as module._name still work, so it is a convention rather than real privacy.
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
- Only the first matching branch runs, and a superclass listed first swallows its subclasses. When two branches could match, the one higher up wins.
- The tuple needs parentheses: except (A, B): is correct, except A, B: is a SyntaxError in Python 3.
- print(e) shows the message; print(e.args) shows a tuple, which for one argument looks like ('message',). The as variable disappears after the except block.
- else means no exception happened; finally means always. If an exception occurs, else is skipped even when the exception was handled.
- Know the parents: ZeroDivisionError under ArithmeticError, IndexError and KeyError under LookupError, ModuleNotFoundError under ImportError, and KeyboardInterrupt directly under BaseException, not Exception.
- raise ValueError and raise ValueError() both work; the class form creates an instance with empty args. A bare raise is valid only while an exception is being handled.
- assert (cond, 'msg') with parentheses is a non-empty tuple and always passes. Also, never rely on assert for input validation, because -O removes it.
- KeyboardInterrupt, SystemExit and GeneratorExit inherit from BaseException, not Exception. Only a bare except or except BaseException (or the specific class) catches them.
- Custom exceptions should derive from Exception. If you override __init__, pass a message to super().__init__() so args and str(e) stay meaningful.
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
- ASCII is a subset of Unicode; UTF-8 is an encoding of Unicode, not a separate character set. A Python str counts code points, so len('é') is 1 even though it takes 2 bytes in UTF-8.
- ord() needs exactly one character, otherwise TypeError. chr() needs an int in range 0 to 0x10FFFF, otherwise ValueError. Remember 'A' = 65, 'a' = 97, '0' = 48.
- Each escape sequence counts as one character: len('\n') is 1 and len('\\') is 1. Watch for accidental escapes in Windows paths.
- Indexing out of range raises IndexError; slicing out of range just clips. With a negative step, start must be greater than stop or the result is empty.
- Any statement that assigns to s[i] or s[a:b], or deletes s[i], raises TypeError for strings. Methods return new strings; if the result is not assigned, it is lost.
- For strings, in tests for a contiguous, case-sensitive substring, and the empty string is always in any string. Mixing types, like 3 in 'a3', raises TypeError.
- '5' == 5 is False without error, but '5' < 5 raises TypeError. In string ordering, uppercase comes before lowercase and '10' < '9'.
- Every is-method returns False for the empty string. isdigit() rejects '-' and '.', and isupper() needs at least one uppercase letter and no lowercase ones, ignoring digits and symbols.
- find returns -1 on failure; index raises ValueError. And join is called on the separator: ', '.join(items), never items.join(', ').
- sorted('abc') returns a list, not a string; join it to get a string. list.sort() returns None, so never assign or print its result expecting a list.
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
- A class is the blueprint; an object is an instance built from it. Subclasses inherit everything from superclasses and may override it, and every class inherits from object.
- obj.x = value always creates or updates an instance variable; it never changes the class variable. Change shared data through the class name.
- Instance __dict__ holds only attributes set on that instance. Class variables and methods live in the class's __dict__, and inherited names do not appear in a subclass's __dict__.
- Inside class C, __x becomes _C__x. Outside the class, obj.__x is not mangled and fails (or creates a separate attribute if assigned). Dunder names like __init__ are never mangled.
- Every instance method needs self as its first parameter, and obj.m(a) passes obj automatically. A second __init__ definition replaces the first; Python has no constructor overloading.
- __name__ and __bases__ belong to classes; on an instance, go through type(obj) or obj.__class__ first. __bases__ lists only direct parents, as a tuple.
- super().method(args) does not take self; ClassName.method(self, args) does. If a subclass overrides __init__ without calling super().__init__(), the parent's attributes are missing.
- In a diamond, the shared ancestor comes after all its subclasses in the MRO. Listing a superclass before one of its own subclasses in the bases raises TypeError when the class is defined.
- issubclass(C, C) is True. isinstance also matches superclasses. a == b compares values; a is b compares identity, and assigning b = a creates no copy.
- print(obj) calls obj.__str__(); without an override you get the default <... object at 0x...> text. Polymorphic calls run the method of the object's actual class, even when called from superclass code.
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
- In multiple for clauses, the leftmost loop is the outer one. A trailing if filters (no else allowed); a leading if ... else transforms every item.
- A lambda body is one expression with an implicit return; no statements, no return keyword. When a function receives a lambda, trace it by substituting the argument into the lambda's expression.
- map and filter return iterators, not lists, and each can be consumed only once. A second list() of the same object gives [].
- Closures remember variables, not snapshots of values. Functions created in a loop all see the loop variable's final value unless you bind it with a default argument.
- Calling a generator function runs none of its body until the first next(). After the last yield, next() raises StopIteration, which for loops absorb silently.
- 'w' erases existing content the moment the file is opened, 'a' preserves it, 'x' fails if the file exists and 'r' fails if it does not. Text mode gives str, binary mode gives bytes.
- print() writes to sys.stdout by default and input() reads from sys.stdin; sys.stderr is separate so errors survive redirection of normal output. All three are open before your program starts.
- End of file is signalled by an empty result ('' or b''), not an exception. write() never adds newlines, and readinto() needs a bytearray and a binary-mode file.
- Compare e.errno with errno module constants, never with raw numbers. ENOENT pairs with FileNotFoundError and EACCES with PermissionError, both subclasses of OSError.
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 planLessons, quizzes, exam simulations and hands-on labs.