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

Free Python Institute PCPP1 - Certified Professional in Python Programming 1 PCPP-32-101 Exam Questions

Last updated: · 11 practice questions with answers and explanations

Page: 1 / 8 Total 45 questions

Want more questions? Get Premium Access.

Question 1

New Single answer

Topic: Advance Object-Oriented Programming

Skill tested: Applies Python method resolution order and super() in cooperative multiple inheritance.

A telemetry application has two mixins that each add a label to a report. Both mixins inherit from a shared base class, and the concrete report class inherits from both mixins. The constructors are designed to cooperate: each accepts the remaining keyword arguments and calls super().__init__(**kwargs). The shared base class accepts a title argument and initializes the report state. A developer wants each constructor in the method resolution order to run exactly once, without hard-coding a particular parent class or skipping the shared base. Which implementation strategy best meets this requirement?

Correct Answer: A. Use super().__init__(**kwargs) in each class, ensuring each constructor consumes its own arguments and forwards the remaining arguments.
Explanation:

Cooperative multiple inheritance relies on every class using super() and forwarding only the arguments it does not consume. Python's method resolution order then visits each class in the chain once, including the shared base, provided the constructors follow the same protocol. Directly naming the base can bypass or duplicate classes in the MRO. Explicitly invoking both mixins and the base also risks repeated initialization. Restarting lookup from type(self) can recurse rather than advance through the MRO.

Question 2

New Single answer

Topic: Advance Object-Oriented Programming

Skill tested: Uses __getitem__ and __len__ to implement Python sequence-style container behavior.

A pricing service exposes a custom Basket object that stores line items internally in a private list. Existing callers need to retrieve an item by integer index, use negative indexes, and call len(basket). The team wants normal list-like indexing behavior, including the built-in IndexError for an out-of-range index, but it does not want to expose the private list or create a separate accessor API. Which minimal implementation most appropriately provides these behaviors?

Correct Answer: C. Implement __getitem__ to return self._items[index] and __len__ to return len(self._items).
Explanation:

Defining __getitem__ delegates integer indexing, negative-index handling, and out-of-range errors to the underlying list. Defining __len__ makes len(basket) report the number of stored items. Iterability alone does not provide integer subscription or length, and __getattr__ handles missing attributes rather than subscription. __contains__ and __bool__ serve different operations and cannot replace the requested sequence behavior.

Question 3

New Multiple answers

Topic: Advance Object-Oriented Programming

Skill tested: Distinguishes class variables from instance variables and evaluates objects with isinstance and issubclass.

A device registry defines Device with a class variable `category = "sensor"`. Its initializer assigns `self.serial` from a supplied value. SpecializedDevice inherits from Device, while Gateway is an unrelated class. A developer creates `d = Device("D-4")`, `s = SpecializedDevice("S-2")`, and `g = Gateway()`. The developer needs to determine whether SpecializedDevice is derived from Device, whether `s` is a Device, and whether the shared category is available through `s` without defining an instance-specific category. Select TWO statements that correctly meet those checks without changing the classes.

Correct Answer: A. `issubclass(SpecializedDevice, Device)` returns True.; B. `isinstance(s, Device)` returns True.
Explanation:

issubclass takes class objects and confirms that SpecializedDevice derives from Device. isinstance takes an object followed by a class or tuple of classes, so `isinstance(s, Device)` is True. An instance can access an inherited class attribute through normal attribute lookup, so `s.category` is available. The argument order in B is reversed, while issubclass in E requires a class as its first argument, not an instance.

Question 4

New Single answer

Topic: Coding Conventions, Best Practices, and Standardization

Skill tested: Applies PEP 8 import organization and module-level import conventions.

A service module imports `os`, `requests`, and two local modules, then performs environment inspection and opens a network connection immediately at module scope. The team is separating reusable code from command-line startup behavior. It wants imports to remain easy to audit and wants importing the module for tests to avoid starting network activity. Which change best follows the relevant Python conventions and meets the requirement?

Correct Answer: A. Keep imports grouped at the top, with standard-library imports, third-party imports, and local imports separated; put startup actions behind a main guard.
Explanation:

PEP 8 recommends imports near the top of the module and grouping standard-library, third-party, and application-specific imports separately. A `if __name__ == "__main__":` guard keeps command-line startup from running when the module is imported by tests or other code. Moving imports into a function is not needed for this goal and does not prevent the module-level connection. Exception handling does not stop that connection attempt, while wildcard imports reduce clarity and the docstring has no bearing on execution.

Question 5

New Single answer

Topic: Coding Conventions, Best Practices, and Standardization

Skill tested: Writes clear docstrings and distinguishes documentation strings from ordinary comments.

A library team is documenting a public function that parses a CSV file and returns records. The function has a required path parameter, may raise an exception when the file is unavailable, and returns a list of dictionaries. The team uses documentation tools that inspect Python objects at runtime and wants the description to be discoverable as the function's documentation string. Which approach is most appropriate?

Correct Answer: D. Place a triple-quoted string as the first statement in the function, describing its behavior, arguments, return value, and relevant exception.
Explanation:

A function docstring is a string literal placed as the first statement in the function body; it is available through the function's `__doc__` attribute and to documentation tools. It should describe the public behavior and relevant parameters, result, and exceptions in the project's chosen style. Inline comments are not collected into `__doc__`. A string after the body is not part of the function, and a module docstring documents the module rather than assigning documentation to each function.

Question 6

New Multiple answers

Topic: Network Programming

Skill tested: Uses socket connection lifecycle, request transmission, and response reception appropriately.

A monitoring utility must retrieve a small HTTP response from a known server using Python's socket module. The endpoint is plain HTTP, the server hostname resolves correctly, and the client is required to connect to the service's HTTP port, transmit an HTTP request, and read the response. The response may arrive in several chunks, and the utility must not assume one recv call returns the entire message. Select TWO actions that correctly address the socket operations and response-reading requirement.

Correct Answer: B. Call recv repeatedly, processing returned bytes until the chosen response-completion condition is reached; account for recv returning fewer bytes than requested.; E. Create a TCP socket, connect it to the resolved server address and HTTP port, and send a properly formed HTTP request.
Explanation:

A conventional HTTP connection uses a TCP stream, so the client creates a stream socket, connects to the server and service port, and sends the request. TCP does not preserve application message boundaries: recv returns up to the requested number of bytes, not necessarily a complete response, so the client must continue reading according to a suitable completion condition. UDP is not the transport for this HTTP exchange. A single recv or send is not guaranteed to process all response or request bytes, respectively.

Question 7

New Single answer

Topic: Network Programming

Skill tested: Selects JSON serialization and deserialization operations for Python data exchange.

A data collector receives a Python dictionary containing strings, numbers, booleans, lists, and nested dictionaries. It must send the data as JSON text over a network connection. A separate component later receives that text and needs an equivalent Python data structure. The implementation must use the standard `json` module and must not confuse text encoding with conversion between JSON and Python objects. Which sequence is appropriate?

Correct Answer: A. Use `json.dumps()` to produce JSON text and `json.loads()` to parse JSON text back into Python objects.
Explanation:

`json.dumps()` serializes a Python object to a JSON-formatted string, suitable for subsequent encoding and transmission. `json.loads()` parses a JSON string and returns corresponding Python objects. The `dump` and `load` variants operate with file-like objects rather than simply returning or consuming a string. `str()` does not guarantee valid JSON, and evaluating received text with eval is unsafe and is not JSON deserialization.

Question 8

New Multiple answers

Topic: File Processing and Communication with a Program's Environment

Skill tested: Uses sqlite3 cursors and transaction commits to persist parameterized database updates.

An inventory application uses SQLite and must update several product quantities from a batch of trusted in-memory records. The table already exists, and each record contains a product ID and a new quantity. The updates should be executed as parameterized SQL, and the batch should be committed as one transaction so other connections can observe it only after successful completion. Which TWO actions should the application take?

Correct Answer: B. Use `cursor.executemany()` with an UPDATE statement containing placeholders and the sequence of parameter tuples.; E. Call `connection.commit()` after the batch has executed successfully.
Explanation:

`executemany()` applies a parameterized statement to each parameter sequence, avoiding manual SQL construction and supporting a batch of updates. Committing the connection after successful execution makes the transaction's changes persistent and visible according to SQLite transaction behavior. Concatenating values into SQL is error-prone and can create injection risks. UPDATE does not produce rows for fetchall in this use, and closing a cursor is not a substitute for committing the connection.

Question 9

New Single answer

Topic: File Processing and Communication with a Program's Environment

Skill tested: Finds repeated XML elements and reads their child text with ElementTree.

A deployment tool parses an XML document whose root contains multiple `` elements. Each server has a `` child, but some documents omit that child. The tool must iterate over every server and collect available names without raising an exception merely because one server has no name element. It uses Python's `xml.etree.ElementTree`. Which approach is most appropriate?

Correct Answer: D. Use `root.findall("server")`, call `server.find("name")` for each server, and check that the returned element exists before reading its text.
Explanation:

`findall("server")` returns all direct child server elements matching that path. For each one, `find("name")` returns the matching child element or None; checking for None avoids dereferencing a missing element. `find` returns only the first match, not every server. The path in C is singular and `find` does not return a list. `findall("name")` on the root does not recursively search arbitrary descendants by default.

Question 10

New Single answer

Topic: File Processing and Communication with a Program's Environment

Skill tested: Writes dictionary records to CSV using DictWriter field names and header handling.

A reporting job writes a CSV file from a sequence of dictionaries with keys `region`, `units`, and `revenue`. The output must have a stable column order, include a header row, and remain readable by spreadsheet applications. The job should use Python's `csv` module rather than manually joining values, because fields can contain commas or quotes. Which implementation choice best satisfies these requirements?

Correct Answer: A. Use `csv.DictWriter` with an explicit ordered `fieldnames` sequence, call `writeheader()`, then write each dictionary with `writerow()`.
Explanation:

`DictWriter` maps dictionary keys to an explicit `fieldnames` order, and `writeheader()` emits those names as the first CSV row. Its CSV writer handles quoting and escaping fields that contain delimiters or quote characters. `DictReader` is for reading rows into dictionaries, and `reader` is likewise a reading interface. Manually joining values does not correctly escape embedded commas, quotes, or line breaks.

Question 11

New Single answer

Topic: File Processing and Communication with a Program's Environment

Skill tested: Configures Python logging levels and formats using LogRecord attributes.

A background worker must write timestamped operational records to a file. Operators need the severity, logger name, and message in each record, and routine informational messages should be included while debug messages remain excluded. The application should use the standard logging framework rather than manually formatting strings at each call site. Which configuration best meets these requirements?

Correct Answer: B. Set the logger level to INFO, attach a file handler, and give it a formatter containing timestamp, `%(levelname)s`, `%(name)s`, and `%(message)s`.
Explanation:

A logger threshold of INFO accepts INFO and more severe records while filtering DEBUG. A file handler directs accepted records to the required file, and a formatter can render timestamp, severity, logger name, and message from LogRecord attributes. DEBUG would include the debug records the operators want excluded. ERROR would suppress informational messages, while standard logging formatters do not automatically capture ordinary print output.