Free PCAP Exam Flashcards
Memorize 50 essential terms and definitions for the OpenEDG PCAP — Certified Associate Python Programmer (PCAP-31-04). See the term, recall the definition, then flip to check yourself.
After 'from math import sqrt as root', which name is available in the importing namespace?
root refers to math.sqrt. That statement does not bind the name math or sqrt locally. In contrast, 'import math' lets you call math.sqrt(9).
Filter by Topic
Jump to Card
About These PCAP Flashcards
These 50 flashcards are designed to help you memorize key terms and definitions for the OpenEDG PCAP — Certified Associate Python Programmer (PCAP-31-04). Each card shows a term on the front and its definition on the back—the classic flashcard format for vocabulary memorization. Use these alongside our practice questions to build both recall and comprehension.
Topics Covered
Complete Flashcard Reference
Review every term in this set. Open any term to reveal its definition.
After 'from math import sqrt as root', which name is available in the importing namespace?
root refers to math.sqrt. That statement does not bind the name math or sqrt locally. In contrast, 'import math' lets you call math.sqrt(9).
What is the difference between sys.path and dir(module)?
sys.path lists locations used for path-based module searches. dir(module) lists names supplied by an already imported module. Use the former to investigate import-location problems and the latter to explore available names.
When does code inside if __name__ == '__main__': run?
It runs when this module is executed as the main program, not on an ordinary import under the module's own name. Put script-only calls inside this guard so the reusable definitions remain importable.
What does __init__.py do in a regular package?
It identifies the directory as a regular package and can execute package initialization code on import. It may be empty. Namespace packages are a separate case and can lack this file.
How do you use a requirements.txt file to set up project dependencies?
Record external packages (often from PyPI) and version constraints in the file, then install with python -m pip install -r requirements.txt in the intended Python environment. Pinning versions helps make installs repeatable.
What is the purpose of .pyc files in __pycache__?
They store cached compiled bytecode for imported modules, reducing repeat compilation at import time. They are not saved program output and do not make the bytecode execute faster than the corresponding uncached bytecode.
With handlers for Exception and ValueError in that order, which catches a ValueError?
The Exception handler catches it first because ValueError derives from Exception. Put a narrower handler before a broader one if it needs distinct behavior.
How can one except clause handle both ValueError and TypeError and inspect the error?
Use except (ValueError, TypeError) as err: followed by the handler body. err is the caught exception; str(err) gives a text representation and err.args holds its argument tuple.
When does a try statement execute its else block versus its finally block?
else runs when try finishes normally, not after a handled exception or an early return, break or continue. finally runs as control exits the try statement, whether the attempt succeeds or fails.
Why is except Exception usually preferable to except BaseException?
Exception catches ordinary application errors, including ValueError and OSError. BaseException also covers termination-related exceptions such as KeyboardInterrupt and SystemExit, which generally should not be swallowed.
What does a bare raise do inside an exception handler?
It re-raises the exception currently being handled. Unless a surrounding handler catches it, it propagates out through callers; this is useful after logging or performing cleanup.
How do you define a custom exception for an invalid order?
Define class InvalidOrder(Exception): pass, then raise InvalidOrder('missing item') when the condition occurs. Catch InvalidOrder where you can recover. Inheriting from Exception integrates it into ordinary error handling.
Why can len('é') differ from len('é'.encode('utf-8'))?
The first counts Unicode code points (1 for this precomposed character); the second counts UTF-8 bytes (2). ord('é') gives its code point, 233, and chr(233) returns 'é'. ASCII covers only the first 128 code points.
If s = 'mint', what happens when you run s[0] = 'h'?
It raises TypeError because strings cannot be mutated. Use s = 'h' + s[1:] to bind s to a new string instead.
Why is 'Zoo' < 'apple' True in Python?
String order compares code points from left to right until the first difference. Uppercase 'Z' has code point 90, while lowercase 'a' has 97. String comparisons are case-sensitive, not dictionary-style sorting.
How do isdecimal(), isdigit() and isnumeric() differ?
They test increasingly broad Unicode character sets. '²'.isdigit() is True but '²'.isdecimal() is False; '½'.isnumeric() is True but '½'.isdigit() is False. All three require a nonempty string.
How do find() and index() respond if the substring does not exist?
find() returns -1; index() raises ValueError. Their rfind() and rindex() counterparts search for the last occurrence. If you need only a presence check, use the in operator.
What is the difference between abstraction and encapsulation?
Abstraction exposes the useful operations while hiding unnecessary complexity. Encapsulation groups data and the methods that manage it, such as an Account object with a deposit method that maintains its balance rules.
How does a class differ from an instance?
A class defines a type and its behavior. An instance is an object of that type with its own identity and potentially its own state. Two separately created instances can hold different attribute values.
Given class Lamp: level = 2, then a = Lamp(); b = Lamp(); a.level = 6, what is b.level?
2. The assignment makes an instance attribute on a that hides the plain class attribute. b still reads Lamp.level. Mutating a shared mutable class attribute, however, can affect all instances using it.
What happens to the attribute self.__count inside class Meter?
Python mangles the name to _Meter__count, which can appear under that key in the instance's __dict__. This helps avoid accidental subclass name clashes, but it does not enforce private access.
Why does an instance method normally declare self as its first parameter?
Calling item.update(3) on an ordinary instance method supplies item as the first argument automatically. self is the conventional parameter name, allowing that method to read or change the receiving object's state.
What should an object's __str__() method return?
A human-readable str describing the object. str(obj) and ordinary print(obj) use it; returning a non-string instead causes a TypeError.
Which built-ins inspect an attribute whose name is held in a string?
getattr(obj, name) fetches the attribute; getattr(obj, name, default) supplies a fallback if it is absent. hasattr(obj, name) reports whether lookup succeeds without AttributeError.
Which class attributes identify its name, defining module and immediate bases?
Class.__name__ is the class name; Class.__module__ identifies the module where it was defined; Class.__bases__ is a tuple of its direct base classes, not its full ancestry.
With ordinary methods and no instance-level shadowing, which method runs when a subclass overrides a base method?
The subclass implementation runs on a subclass instance. The same call can behave differently on another subclass, a form of polymorphism. The overriding method can extend inherited behavior using super().
In a diamond where B and C each inherit A, and D inherits (B, C), what is D's MRO?
D, B, C, A, object, for these simple classes. Method resolution order determines the class lookup sequence. super() proceeds to the next implementation in the MRO, which is not necessarily a direct parent.
Why does isinstance(child, Parent) return True for an ordinary Child(Parent) instance?
isinstance() recognizes inherited types, unlike type(child) is Parent. Polymorphic code can work with the shared behavior of different subclasses rather than require the exact same concrete type.
Given a = [4]; b = [4], how do a == b and a is b differ?
a == b is True because the lists contain equal values. a is b is False because separately created lists are different objects. Assigning b = a would make both names refer to one list.
If a subclass defines its own __init__, how can it initialize the inherited state?
Call super().__init__(...) with the arguments expected by the next initializer in the MRO. Defining a subclass initializer does not automatically execute the overridden base initializer.
Why avoid def __init__(self, items=[]) for per-instance lists?
The default list is created when the function is defined, so omitted arguments can share that list across instances. Use items=None and create a new list inside __init__ when items is None.
What is the result of {n: n * 2 for n in range(5) if n % 2 == 1}?
{1: 2, 3: 6}. The if clause selects odd inputs, and the key:value expression supplies the dictionary entries. A list comprehension instead uses square brackets with one output expression.
What is the result of [v for row in [[8, 2], [5]] for v in row]?
[8, 2, 5]. Read the for clauses in their written order as nested loops: first select a row, then iterate over its values. The expression produces a flattened list.
In a match statement, what does case [first, second]: do?
It matches a compatible two-element sequence such as a list or tuple and binds the two names. Python executes the first matching case whose guard, if any, is true. A final case _: can handle otherwise unmatched values.
When does the else clause of a for loop execute?
When the iterable is exhausted normally, even if it was empty. A break skips the else clause; so does leaving the loop by return or an uncaught exception. This is useful for reporting an unsuccessful search.
What does lambda value: value * 3 create?
A function object accepting value and returning the expression value * 3. If saved as triple, triple(4) returns 12. A lambda body must be one expression; use def when multiple statements are needed.
How do map() and filter() differ in Python 3?
map(fn, values) produces results of applying fn to values. filter(pred, values) yields original elements for which pred is truthy. Both return iterators, so use list(...) if you need a materialized list.
What allows a returned inner function to remember an enclosing variable?
A closure retains access to the enclosing scope's binding. For example, a function factory can bind a tax rate in its outer function and return an inner calculator using that rate. Captured bindings are not automatic frozen copies.
Which open() mode appends without discarding existing content, and which requires a new file?
Use 'a' to append, or 'x' for exclusive creation (raises FileExistsError if the file exists). 'w' instead truncates an existing file; use it only when replacing the contents is intended.
What differs between reading a file with 'r' and with 'rb'?
A text-mode stream ('r') reads str values after decoding; specify an encoding such as UTF-8 when appropriate. A binary stream ('rb') reads bytes without text decoding or newline translation.
What does a with open(...) as f: block guarantee about the file on exit?
After a successful open, the file context manager closes it when control leaves the block, even if an exception occurs. The exception normally still propagates unless a handler catches it.
What happens after buf = bytearray(b'ABC'); buf[1] = 90?
buf contains bytearray(b'AZC'). bytearray is mutable and each indexed byte is an integer from 0 to 255. The bytes type is immutable.
How can pathlib join a directory path with a filename and read the text?
Use p = Path('notes') / 'index.txt' after importing Path from pathlib. p.read_text(encoding='utf-8') returns the file's decoded contents and closes the file. This relative path is resolved against the working directory.
What makes a good unit test for a function that accepts ages from 18 to 65 inclusive?
Check a specific expected behavior in isolation. For example, test an ordinary valid age, boundary inputs 18 and 65, and invalid neighbors 17 and 66 in separate cases. Rerun the tests after changes to catch regressions.
Why is assert not a reliable substitute for validating user input?
A failed assert normally raises AssertionError. Python's optimization option -O can remove assert statements, so mandatory input checks should use explicit conditions and exceptions. Assertions suit development-time invariants.
How can you distinguish a logic error from a runtime exception during debugging?
A logic error produces unintended behavior without necessarily raising an exception. A runtime exception interrupts normal execution; inspect the traceback for its type and call locations. A syntax error can prevent the code from running in the first place.
Why make a Git branch for an isolated change instead of editing a shared branch directly?
A branch lets you develop and commit a change separately. A pull or merge request proposes its integration and gives teammates a chance to review. Coordinate overlapping changes to prevent or resolve merge conflicts.
What is continuous integration (CI) used for before merging a change?
CI runs agreed automated checks, such as tests, on proposed or integrated changes. Failures provide early feedback; passing checks are useful evidence but do not replace reviewing the code against its requirements.
What information makes an AI-assisted coding request easier to verify?
Describe the intended behavior, constraints, relevant context, example inputs and expected outputs. This makes the proposed solution testable against explicit requirements instead of relying on a vague request.
What must a developer do before accepting AI-generated Python code?
Read it, verify referenced APIs in documentation, test expected and failing cases, and check for unsafe behavior before approval. Keep credentials and sensitive data out of prompts. The developer remains responsible for the accepted code.
Frequently Asked Questions
Which PCAP exam version do these flashcards cover?
These cards cover PCAP-31-04, released October 31, 2026. PCAP-31-03 remains available until November 30, 2027 and has a different syllabus, so check the exam code on your voucher. When using material labeled PCAP-31-03, consult the PCAP-31-04 syllabus for the new objectives.
How many questions are on PCAP-31-04 and what score is needed?
PCAP-31-04 has 42 questions with 65 minutes of testing time and a passing score of 72%. The earlier PCAP-31-03 has 40 questions and a 70% passing score.
Which PCAP-31-04 topics carry the most weight?
Object-oriented programming carries 28.5%, advanced Python constructs and I/O 24%, testing, debugging, collaboration and AI assistance 14%, modules and packages 12%, exceptions 12%, and strings 9.5%. The weights are not necessarily the same as the percentages of questions.
Do I need PCEP before taking PCAP?
No. PCEP certification or comparable foundational Python skills are recommended, not mandatory. PCAP-31-04 can be taken directly through TestNow if you meet the testing policies.
Does PCAP certification expire?
PCAP-31-04 credentials are valid for five years. PCAP-31-03 awards a lifetime credential. A new exam version does not retroactively shorten the validity of a certificate already issued.
Can I retake PCAP after failing?
The PCAP-specific testing policy requires a 15-day wait following each failed attempt and sets no cap on failed-exam retakes. A new voucher may be necessary.
How should I use these cards?
Recall the rule or predict each code result before flipping the card. Then run small original Python examples, especially for inheritance, exception flow, path operations and tests. Use the official syllabus to check your coverage.
Explore More OpenEDG Python Institute Certifications
Continue into nearby exams from the same family. Each card keeps practice questions, study guides, flashcards, videos, and articles in one place.
More From This Family
Videos and articles for deeper review.