Limited-Time Offer: Enjoy 50% Savings! Coupon code: 50OFF Use it at checkout
Skip to content

Free Python Institute Certified Associate in Python Programming Exam PCAP-31-03 Exam Questions

Last updated: · 13 practice questions with answers and explanations

Page: 1 / 11 Total 154 questions

Want more questions? Get Premium Access.

Question 1

New Single answer

Topic: Modules and Packages

Skill tested: Resolves nested package imports using package-qualified names and import search paths.

A data-processing application has this layout: `app.py`, `analytics/__init__.py`, `analytics/reports/__init__.py`, and `analytics/reports/summary.py`. The `summary.py` module defines `build()`. The application is launched with its working directory set to the directory containing `app.py`. A developer wants `app.py` to call `build()` without modifying `sys.path` or relying on the process working directory beyond this launch arrangement. Which import statement is the most appropriate?

Correct Answer: B. `from analytics.reports import summary`; then call `summary.build()`
Explanation:

The directory containing the launched top-level script is placed on the module search path, so `analytics` can be imported as a top-level package. The fully qualified import follows the directory/package nesting and binds the `summary` module for the subsequent call. Importing `summary` alone does not find it at the top level, and reversing the package order does not match the layout. A leading-dot relative import is intended for use from within a package module; `app.py` is the top-level script here.

Question 2

New Multiple answers

Topic: Modules and Packages

Skill tested: Uses Python platform functions to report interpreter and operating-system characteristics.

A deployment diagnostic tool must emit the Python implementation name, Python version components as a tuple, and the operating-system name. It must work across supported Python implementations and must not parse human-readable version strings. Which two approaches meet these requirements? Select TWO.

Correct Answer: B. Use `platform.python_implementation()`, `platform.python_version_tuple()`, and `platform.system()`.; D. Use `platform.python_implementation()`, `platform.python_version_tuple()`, and `platform.system()`; these provide the requested values without parsing display strings.
Explanation:

Both A and E identify the same suitable functions: `python_implementation()` reports the interpreter implementation, `python_version_tuple()` supplies version components, and `system()` reports the operating system name. The tuple avoids parsing a formatted version string. `processor()` and `machine()` describe hardware-related information, while `version()` describes the operating-system version rather than Python's version tuple. `sys.version` is a display string and does not directly provide the requested implementation name or tuple.

Question 3

New Single answer

Topic: Exceptions

Skill tested: Orders specific and general exception handlers to preserve intended exception handling.

A command-line importer converts user input to an integer and then indexes a list of records. The code should print a specific message for invalid integer input, a different message when the integer is outside the list, and a final message only when the operation succeeds. The developer currently places `except Exception` before handlers for `ValueError` and `IndexError`, so those specific messages never appear. What is the best correction?

Correct Answer: A. Place the `ValueError` and `IndexError` handlers before `except Exception`, and put the success message in an `else` clause.
Explanation:

Python selects the first matching `except` clause, and `Exception` is a superclass of both `ValueError` and `IndexError`. Specific handlers must therefore precede the broad handler. An `else` clause runs only when the `try` suite completes without raising, which matches the success-message requirement. Re-raising after the broad handler does not allow later handlers in the same `try` statement to catch that exception. Including `Exception` in the tuple makes the specific handlers redundant, and `finally` runs regardless of success or failure.

Question 4

New Single answer

Topic: Exceptions

Skill tested: Raises and catches a custom exception while preserving its attached error argument.

A library validates sensor readings and defines a custom exception, `ReadingError`, derived directly from `Exception`. When a reading is invalid, the validator raises `ReadingError("sensor-7", "out of range")`. The calling service needs to catch only this validation failure, obtain the exception's arguments as a tuple, and leave unrelated exceptions to propagate. Which handler satisfies the requirement?

Correct Answer: C. `except ReadingError as e: values = e.args`
Explanation:

Catching `ReadingError` specifically handles the library's validation failure without swallowing unrelated exceptions. The `as e` binding refers to the raised exception instance, and its `args` attribute contains the positional arguments passed to the exception constructor - in this case, the sensor identifier and message. Catching `Exception` is broader than required, and adding it to a tuple still catches nearly all ordinary application exceptions. Accessing `ReadingError.args` examines the class rather than the particular raised instance.

Question 5

New Single answer

Topic: Strings

Skill tested: Applies Unicode code points, ord, chr, and UTF-8 encoding distinctions.

A logging service receives the character `é` as a Python string and needs to store its Unicode code point and its UTF-8 bytes separately. A developer proposes using `ord()` for the code point and `encode("utf-8")` for the bytes, but another developer says a Python string is already UTF-8 encoded. Which description correctly guides the implementation?

Correct Answer: C. `ord("é")` returns the code point 233; `"é".encode("utf-8")` returns its UTF-8 byte representation, which contains two bytes.
Explanation:

A Python `str` represents Unicode text, and `ord()` returns the Unicode code point of a single character. For `é`, that value is 233. UTF-8 is an encoding that converts the text to a `bytes` object; this character is represented by two UTF-8 bytes. `chr(233)` converts the code point back to a one-character string, not encoded bytes. Encoding does not turn a string into another string, and it is distinct from the string's Unicode representation.

Question 6

New Multiple answers

Topic: Strings

Skill tested: Chooses string search and sorting operations without mutating immutable string data.

A monitoring tool receives a string containing space-separated service names. It must determine whether the substring `api` occurs, locate the last occurrence of `api`, and produce an alphabetically sorted list of the names without changing the original string. The input may omit `api`, and the tool must distinguish that case without raising an exception. Which TWO approaches meet the requirements? Select TWO.

Correct Answer: D. Use `sorted(text.split())` to produce a sorted list while leaving `text` unchanged.; E. Use `"api" in text` for the presence check and `text.rfind("api")` for the last-position search.
Explanation:

The membership operator provides a direct Boolean presence test, and `rfind()` returns the index of the last match or `-1` when there is no match, so absence does not raise an exception. `split()` produces a list of names, and `sorted()` returns a new sorted list without modifying the immutable original string. `index()` raises `ValueError` when absent and returns the first match, not the last. Strings do not have a mutating `sort()` method, while sorting the characters with `sorted(text)` would not sort the service-name tokens.

Question 7

New Single answer

Topic: Strings

Skill tested: Uses slicing and iteration correctly while respecting string immutability.

A data-cleaning routine receives a string whose first and last characters are delimiters. It must create a new string containing only the interior characters, then replace every lowercase `x` in that result with `y`. The original input must remain available for audit logging. Which approach correctly satisfies these requirements?

Correct Answer: A. Assign `text[1:-1]` to a new variable, then call `replace("x", "y")` and assign the returned string.
Explanation:

Slicing creates a new string containing the requested interior, and `str.replace()` returns another string with the replacements applied. Assigning that return value preserves the transformed result while leaving the original string untouched. Strings are immutable: characters cannot be deleted or assigned in place, and `replace()` does not mutate its receiver. The `sort()` method is not available on strings and, in any event, would not perform the requested replacement.

Question 8

New Single answer

Topic: Object-Oriented Programming

Skill tested: Distinguishes instance attributes from class attributes and predicts attribute lookup results.

A fleet-monitoring application defines `class Device` with a class attribute `status = "idle"`. It constructs two devices, `north` and `south`, and then executes `north.status = "active"`. The developer needs to understand what `south.status`, `Device.status`, and `north.__dict__` contain before making a change to the model. Which description is accurate?

Correct Answer: D. `north.status` is `"active"`; `south.status` and `Device.status` remain `"idle"`; `north.__dict__` contains the instance attribute `status`.
Explanation:

Attribute lookup finds an instance attribute before consulting the class. Assigning `north.status` creates an entry in that instance's namespace, shadowing the class attribute for `north` alone. The class attribute remains `"idle"`, so `south` still obtains that value through class lookup, and `Device.status` is unchanged. The class's original definition does not prevent an instance from acquiring its own attribute, and the assignment does not modify the class namespace.

Question 9

New Single answer

Topic: Object-Oriented Programming

Skill tested: Applies name mangling and inheritance rules to class-private attributes.

A base class `Account` defines `self.__balance = 100` in its constructor and a method `balance()` that returns `self.__balance`. A subclass `AuditedAccount` also defines `self.__balance = 0` for a separate audit counter. After constructing an `AuditedAccount`, the service calls `balance()` and inspects the instance dictionary. Which behavior should it expect under Python's name-mangling rules?

Correct Answer: C. The base method returns 100; the two attributes have distinct mangled names associated with `Account` and `AuditedAccount`.
Explanation:

A name beginning with two underscores and not ending with two underscores is mangled using the class in which it appears. The base class's `__balance` and subclass's `__balance` therefore refer to distinct attribute names. The `Account.balance()` method accesses the base-class-mangled attribute and returns 100, while the subclass attribute stores its separate counter. Name mangling helps avoid accidental name collisions; it is not access control that prevents the defining class's methods from using the attribute.

Question 10

New Multiple answers

Topic: Object-Oriented Programming

Skill tested: Interprets method resolution order and inheritance relationships in a diamond hierarchy.

A reporting library uses a diamond hierarchy: `class Root`, `class Left(Root)`, `class Right(Root)`, and `class Report(Left, Right)`. Both `Left` and `Right` override `label()`, and each calls `super().label()` before adding its own prefix. `Root.label()` returns `"root"`. A maintainer wants cooperative behavior in which each implementation participates once according to Python's method resolution order. Which TWO statements are accurate? Select TWO.

Correct Answer: B. For `Report`, the method resolution order is `Report`, `Left`, `Right`, `Root`, then `object`.; D. If each override calls `super().label()`, the calls can proceed through `Left`, then `Right`, then `Root` for a `Report` instance.
Explanation:

Python's C3 method resolution order for this consistent diamond is `Report`, `Left`, `Right`, `Root`, and `object`. A cooperative `super()` call continues to the next class in that instance's MRO, so `Left` can delegate to `Right`, which delegates to `Root`. It does not mean "call my lexical parent directly." A valid diamond is supported when its MRO is consistent, and indirect inheritance still makes a `Report` instance an instance of `Root`.

Question 11

New Single answer

Topic: Object-Oriented Programming

Skill tested: Uses object introspection to check attributes and distinguish class metadata from instance identity.

A plugin manager accepts objects only when their class defines a callable `start` attribute and belongs to a class derived from `Plugin`. The manager must reject an object that merely happens to have a `start` attribute added to that instance at runtime. Which implementation most directly enforces both requirements?

Correct Answer: A. Check `hasattr(type(obj), "start")` and `isinstance(obj, Plugin)`.
Explanation:

Checking `hasattr(type(obj), "start")` looks for the attribute on the object's class or its class hierarchy, rather than accepting an attribute attached only to that particular instance. `isinstance(obj, Plugin)` also accepts instances of subclasses, as required. `hasattr(obj, "start")` alone may succeed because of a runtime instance attribute. The `is` operator compares object identity, not inheritance, and ordinary instances do not use `__name__` as their class name.

Question 12

New Single answer

Topic: Object-Oriented Programming

Skill tested: Implements string representation through the special __str__ method.

A command-line inventory report prints each `Item` object directly. The current output resembles ``, but operators need a stable, readable line containing the item's SKU and quantity. The application should preserve normal object behavior elsewhere and should not require every caller to format fields manually. What is the best design change?

Correct Answer: C. Define `__str__(self)` on `Item` to return a formatted string containing the SKU and quantity.
Explanation:

`print()` converts its argument to text using `str()`, which calls the object's `__str__()` method when defined. Returning a formatted string there gives callers readable output without changing construction or requiring each caller to duplicate formatting logic. `__str__` must return a string; printing from `__repr__` and returning `None` violates the representation method's contract. `__name__` describes a class or function name, not an instance's display format, and `__init__` initializes an object rather than supplying its printed representation.

Question 13

New Multiple answers

Topic: Miscellaneous (List Comprehensions, Lambdas, Closures, and I/O Operations)

Skill tested: Uses comprehensions, map, and filter to transform and select sequence values.

A telemetry pipeline receives a list of integer readings. It must first retain only positive readings, then convert each retained reading to its square, producing a new list while leaving the input unchanged. The team is comparing idiomatic Python approaches and wants approaches that preserve the required filter-before-transform behavior. Which TWO implementations meet the requirements? Select TWO.

Correct Answer: B. `[x * x for x in readings if x > 0]`; C. `list(map(lambda x: x * x, filter(lambda x: x > 0, readings)))`
Explanation:

The comprehension filters each original value with `x > 0` and squares only values that pass. The `filter()` call in B likewise selects positive inputs before `map()` transforms them, and converting the iterator to a list produces the requested new list. C filters squared values, so negative readings become positive and are incorrectly retained. D mutates the input by sorting it, violating the constraint. E also retains negative nonzero readings because their squares are positive.