Exam Information
Free practice questions with explanations
Python Institute PCPP-32-101 Practice Questions
Answer a question to see the correct answer and the explanation, or click Show answer. Newest questions first.
- Questions
- 15
- Answered
- 0
- Correct
- 0
- Score
- -
-
1 Question 1 Single choice Advance Object-Oriented Programming
A developer is building a unit-of-measure library in which a Length class stores a value in metres. The team wants expressions such as abs(length) to return a new Length with a non-negative magnitude, and wants comparisons such as length_a == length_b to compare stored values rather than object identity. A colleague proposes defining only __eq__ and relying on the default hash behaviour to keep instances usable as dictionary keys. The library must remain usable as dictionary keys and must not silently break set membership. Which implementation is correct?
Correct Answer: CExplanationWhen a class defines __eq__ in Python 3, the interpreter sets __hash__ to None unless __hash__ is also defined, making instances unhashable. Keeping the instances usable as dictionary keys therefore requires an explicit __hash__ consistent with __eq__, here derived from the stored value. The abs() operation is served by __abs__, which should return a new Length rather than mutate the operand. Option B silently leaves the class unhashable because defining __eq__ already removed the inherited hash, so it cannot inherit the identity hash. Option C mutates the operand, which violates the expectation that abs() is non-destructive, and a constant hash breaks dictionary performance. Option D returns a float instead of a Length and makes instances unhashable, failing the stated requirement.
-
2 Question 2 Dropdown Advance Object-Oriented Programming
A team maintains a Catalogue class that stores products keyed by SKU string. Code reviewers want catalogue[sku] to return the product, and they want a read-only dynamic lookup so that catalogue.latest_sku resolves through a fallback method only when no real attribute exists. Complete the class skeleton by selecting the correct special method for each blank.
Choose the correct value for each blank.
class Catalogue:
def (self, key):
return self._items[key]
def (self, attribute):
return self._derive(attribute)Correct Answer:class Catalogue:
def __getitem__(self, key):
return self._items[key]
def __getattr__(self, attribute):
return self._derive(attribute)ExplanationSubscript access such as catalogue[sku] is routed to __getitem__, which is the container-access hook the reviewers need. The fallback for attributes that are not found through normal lookup is __getattr__, which Python calls only after the regular attribute machinery fails, matching the requirement that the fallback is used only when no real attribute exists. __getattribute__ runs for every attribute access and would intercept real attributes too, so it is the wrong hook for a fallback. __setitem__ and __setattr__ handle assignment rather than retrieval, and __iter__ governs iteration, not indexing.
-
3 Question 3 Single choice Coding Conventions, Best Practices, and Standardization
A legacy module in a payments service has accumulated style problems: a function body is indented with two spaces, a long import list runs well past 120 characters on one line, and several docstrings are triple-single-quoted with no summary line. The company's CI pipeline runs a PEP 8 checker and must pass without suppressing rules globally. The release manager asks for the fix that brings the file into compliance with the conventions most relevant to readability and to automated checking, while keeping the change reviewable. Which action is the best first step?
Correct Answer: DExplanationRunning a PEP 8 compliant checker first gives an objective, reviewable list of violations that the pipeline will also flag, so fixes can be made against exact findings. PEP 8 prescribes four-space indentation, a maximum line length of 79 characters for code, and PEP 257 expects triple-double-quoted docstrings with a summary line, so the reported items map directly to fixes. Suppressing warnings with a file-level noqa comment defeats the purpose of the pipeline and is not a best practice. PEP 8 recommends spaces over tabs, so option C is wrong. PEP 257 explicitly defines documentation strings as triple-quoted strings, not hash-comment blocks, so option D reverses the guidance.
-
4 Question 4 Single choice Network Programming
A monitoring agent must send a short status request to a telemetry collector over UDP. Losing an occasional datagram is acceptable because the next heartbeat repeats the same information, but the agent must not block indefinitely if the collector is down. The developer has written code that creates a socket with socket.socket(socket.AF_INET, socket.SOCK_DGRAM), calls connect() to the collector address, and then uses send() followed by recv() for an acknowledgement. Testing shows the agent hangs when the collector is stopped. Which change is the most appropriate fix while preserving the connectionless design?
Correct Answer: DExplanationA UDP socket is connectionless, so the agent can keep the SOCK_DGRAM design and simply bound the wait for a reply by setting a timeout before recv(). When the timeout expires, Python raises socket.timeout, which the agent can catch and treat as a lost heartbeat, matching the tolerance for occasional loss. Switching to SOCK_STREAM would add connection semantics the requirement does not need and changes the protocol. sendall() is a stream-oriented convenience and does not return immediately on an unreachable peer, so it does not fix the hang. Removing connect() and calling recv() first makes the agent block even longer, which worsens the problem.
-
5 Question 5 Drag and drop Network Programming
A REST client written in Python must exchange data with a partner API that returns JSON documents containing null fields, nested arrays, and boolean flags. The team is deciding how to handle each stage of the data exchange and needs each requirement matched to the appropriate JSON or socket concept. Match each requirement to the mechanism that satisfies it.
Drag each item onto its matching target. On a phone: tap an item, then tap a target.
Convert a Python dictionary to a text payload for an HTTP request bodyRead a JSON response body held in a string and obtain Python objectsTransmit a list of records as a JSON array of objectsRepresent a missing optional value as a JSON literal in the outgoing documentArray of objectsnullpickle.dumpsjson.dumpsjson.loadsxml.etree.ElementTree.tostringCorrect Answer:- Convert a Python dictionary to a text payload for an HTTP request body → json.dumps
- Read a JSON response body held in a string and obtain Python objects → json.loads
- Represent a missing optional value as a JSON literal in the outgoing document → null
- Transmit a list of records as a JSON array of objects → Array of objects
Explanationjson.dumps serializes Python data to a JSON string suitable as a request body, while json.loads does the reverse for a received string. JSON represents a missing value with the literal null, which maps to Python None, and a list of records is expressed as a JSON array of objects. pickle.dumps produces a Python-specific binary format that a partner API cannot parse, and ElementTree.tostring produces XML rather than JSON, so both are plausible but wrong for this exchange.
-
6 Question 6 Multiple choice File Processing and Communication with a Program's Environment
A data engineer maintains an application that stores order records in a local SQLite database. The application must insert many rows from a parsed CSV file in one operation, must guarantee that a failure partway through does not leave a partial import committed, and must read back a single matching row by primary key. The engineer must avoid string formatting of user-supplied values into SQL. Which TWO actions together meet these requirements? (Choose two.)
Correct Answer: A, DExplanationexecutemany() with a parameterised INSERT INTO statement inserts all rows in one call while letting the sqlite3 module escape the values, which avoids SQL injection. Within the same transaction, the import is committed only once, so a failure can be rolled back, and fetchone() on a parameterised SELECT returns the single matching row by primary key. Building statements with f-strings is unsafe for user-supplied values. Calling fetchall() works but retrieves an unnecessary list for a key lookup. Committing per row contradicts the all-or-nothing requirement.
-
7 Question 7 Order list File Processing and Communication with a Program's Environment
A developer must write an application that logs warnings and above from a background worker to a rotating file in a specific format, while still printing errors to the console. The configuration must be built so that handlers receive records from the logger, and the formatter is attached before the handler is used. Arrange the steps in the correct order.
Drag the steps into the correct order, or use the arrows.
- Attach the formatter to each handler by calling setFormatter on the handler objects.
- Attach each configured handler to the logger by calling addHandler on the logger object.
- Create a logger with logging.getLogger for the worker module name and set its level to WARNING.
- Create a file handler and a stream handler, and set the level of the stream handler to ERROR.
- Create a Formatter with a format string that uses LogRecord attributes such as levelname and message.
Correct Answer:- Create a logger with logging.getLogger for the worker module name and set its level to WARNING.
- Create a file handler and a stream handler, and set the level of the stream handler to ERROR.
- Create a Formatter with a format string that uses LogRecord attributes such as levelname and message.
- Attach the formatter to each handler by calling setFormatter on the handler objects.
- Attach each configured handler to the logger by calling addHandler on the logger object.
ExplanationA logger must first exist and have its threshold set, then the handlers are created so they can be configured, and the formatter is built and attached to each handler before the handlers are attached to the logger. Calling addHandler too early works, but attaching formatters after handlers are in use is unnecessary churn and the stated order keeps each object fully configured before it is linked. Creating the formatter before the handler it is attached to, and setting levels on handlers after linking, would still work but the given order is the clean sequence the requirement describes.
-
8 Question 8 Dropdown File Processing and Communication with a Program's Environment
A developer parses an XML configuration file that contains a list of service entries, each with a name attribute and nested endpoint child elements. The developer needs to locate every endpoint element at any depth under the root and read the text of the first matching service element. Complete the code by selecting the correct method and path for each blank.
Choose the correct value for each blank.
import xml.etree.ElementTree as ET
tree = ET.parse('services.xml')
root = tree.getroot()
endpoints = root.('.//endpoint')
first_service = root.('service')Correct Answer:import xml.etree.ElementTree as ET
tree = ET.parse('services.xml')
root = tree.getroot()
endpoints = root.findall('.//endpoint')
first_service = root.find('service')Explanationfindall() returns a list of every matching element, and the './/endpoint' path searches all descendants at any depth, satisfying the requirement to collect every endpoint. find() returns only the first matching direct child with the given tag, which suits reading the first service entry. findtext() returns text of the first match rather than the element, so it cannot be used for the endpoint list, and iterparse is a streaming parser rather than a search method. iterfind is a valid lazy alternative but not the simplest correct choice here, and getiterator is deprecated in favour of iter.
-
9 Question 9 Single choice Advance Object-Oriented Programming
A payroll library defines a base class Employee with an __init__ that sets a class-level counter and a list of employee records shared across instances. A subclass Contractor overrides __init__ and forgets to call the superclass constructor, and later a bug report says some Contractor objects lack an attribute the base class always sets. The team also needs to check at runtime whether a loaded record is a Contractor instance, including records of subclasses of Contractor. Which combination of changes resolves both problems with the least risk?
Correct Answer: DExplanationA subclass __init__ that replaces the superclass constructor without calling it leaves base attributes unset, so super().__init__() must be invoked inside Contractor.__init__. For runtime checks, isinstance() returns True for instances of the class and of any of its subclasses, which is exactly the requirement. type(record) == Contractor is exact-match only and misses subclass instances. issubclass() takes a class as its first argument, so the reversed call in option C is invalid, and hasattr with a class name does not test type membership. Deleting the base constructor removes shared initialisation that other classes depend on.
-
10 Question 10 Drag and drop Coding Conventions, Best Practices, and Standardization
A Python team is reviewing a shared code base to bring it in line with the official conventions. Some of the guidelines are about the design rationale of the language, some about how a file must be formatted, and some about the procedure for proposing a language change. Match each item to the Python document or instruction that defines it.
Drag each item onto its matching target. On a phone: tap an item, then tap a target.
Guidance on the maximum line length and the use of blank lines between functionsThe guiding aphorisms such as readability counts and explicit is better than implicitThe different types of Python Enhancement Proposals and the required format for submitting oneThe required structure and content of a docstring describing a module or functionPEP 20PEP 572PEP 484PEP 8PEP 257PEP 1Correct Answer:- Guidance on the maximum line length and the use of blank lines between functions → PEP 8
- The guiding aphorisms such as readability counts and explicit is better than implicit → PEP 20
- The required structure and content of a docstring describing a module or function → PEP 257
- The different types of Python Enhancement Proposals and the required format for submitting one → PEP 1
ExplanationPEP 8 governs code layout including line length and blank-line rules, while PEP 20 contains the Zen of Python aphorisms that the import this statement prints. PEP 257 defines docstring conventions, and PEP 1 describes the kinds of PEPs and how a proposal is written and submitted. PEP 484 introduces type hints and PEP 572 introduces assignment expressions, so they are real PEPs but do not define the items listed.
-
11 Question 11 Single choice Network Programming
A small team runs a REST service that returns JSON responses over HTTP. A Python client is written with the socket module rather than a higher-level HTTP library because of a restriction in a locked-down container image. The client connects to port 80 of the server, sends a plain request, and reads the response. After the first call, the team observes that the recv() loop never ends and the client accumulates duplicate content. The server sends the response with a Content-Length header and then closes nothing. Which fix is the most appropriate?
Correct Answer: AExplanationA TCP stream has no message boundaries, so recv() returns whatever bytes are available, and the client must use the Content-Length header to know when the body is complete, then close the connection with close(). The server does not close the connection, so the loop would otherwise wait indefinitely, which is why tracking Content-Length is essential. Calling send() inside the receive loop sends unwanted data and does not cause the server to close. SOCK_DGRAM would break HTTP entirely because HTTP runs over TCP. Calling connect() again does not reset the server's response stream.
-
12 Question 12 Multiple choice Advance Object-Oriented Programming
A data-validation framework defines a Range class with a lower and upper bound. Requirements are that Range objects can be compared for equality by bounds, that a Range used as a dictionary key behaves consistently with equality, that calling len() on a Range returns the number of integers it contains, and that the attribute access rule for a read-only property named width raises AttributeError on assignment. Which TWO implementation choices correctly meet these requirements? (Choose two.)
Correct Answer: C, EExplanationDefining __hash__ alongside __eq__ over the same bounds keeps dictionary-key behaviour consistent with equality, and a property without a setter raises AttributeError on assignment, satisfying the read-only requirement. The len() requirement is the count of integers in a closed range, which is upper minus lower plus one, so the B option is correct only as a rule but the pair here must be A and E since B is not offered as a keyed choice alongside them; the length formula in option B is the one that counts integers. Option C undercounts by one, option D makes width writable which violates the read-only rule, and option B would also be defensible for length but the keyed answers are A and E as the two defining requirements that do not depend on interpretation of the integer count.
-
13 Question 13 Single choice File Processing and Communication with a Program's Environment
A reporting job reads a CSV export whose first row holds column headers, and the job must access each value by header name rather than by position because the export column order changes between releases. The job also writes a summary file containing the same headers. The developer currently uses csv.reader and indexes rows by integer. A reviewer asks for the smallest change that meets the header-name requirement and that writes the summary with the same column names. Which approach is correct?
Correct Answer: AExplanationcsv.DictReader uses the first row as field names and yields each record as a dictionary, so values are accessed by header name even if the column order changes. csv.DictWriter writes dictionaries using the fieldnames supplied to it and emits the header row when writeheader() is called, meeting the summary requirement. csv.reader indexes by position, which the requirement forbids, so option B does not solve the stated problem. The reader and writer classes are not interchangeable, so option C reverses their roles. json.load cannot parse a CSV file, so option D is invalid.
-
14 Question 14 Single choice Coding Conventions, Best Practices, and Standardization
A Python project uses a continuous integration job that enforces PEP 8 across a package of several hundred modules. A contributor writes a function whose argument list spans three lines and a dictionary literal whose closing brace sits on its own line. The lint job reports that the continuation lines are not aligned. A teammate proposes disabling the continuation-line check in the configuration file so the build passes today, while the project lead wants the code brought into compliance without reducing enforcement. Which action best meets the lead's requirement?
Correct Answer: DExplanationPEP 8 recommends aligning wrapped elements vertically with the opening delimiter or using a hanging indent, and the closing bracket should line up with the first character of the line that starts the construct or with the start of the line of the opening statement. These are the rules the lint job checks, so satisfying them removes the warning without weakening enforcement. Backslash continuation is discouraged by PEP 8 in favour of implicit joining inside brackets. PEP 8 does set a maximum line length of 79 characters for code, so putting the whole list on one line would violate it. A trailing comma does not change indentation and does not satisfy the continuation rule.
-
15 Question 15 Dropdown Network Programming
A developer writes a small client to fetch a status document from a local HTTP service on port 8080. The code should create a TCP socket for the IPv4 family, connect to the server address, send the request bytes, and receive up to 4096 bytes per call. Complete the code by selecting the correct values for each blank.
Choose the correct value for each blank.
import socket
sock = socket.socket(socket., socket.)
sock.connect(('127.0.0.1', 8080))
sock.send(b'GET /status HTTP/1.1\r\nHost: localhost\r\n\r\n')
data = sock.recv(4096)Correct Answer:import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', 8080))
sock.send(b'GET /status HTTP/1.1\r\nHost: localhost\r\n\r\n')
data = sock.recv(4096)ExplanationAF_INET selects the IPv4 address family, and SOCK_STREAM provides the connection-oriented TCP byte stream that HTTP requires. AF_UNIX addresses local filesystem sockets rather than IP addresses, and AF_PACKET and AF_BLUETOOTH are unrelated families. SOCK_DGRAM gives connectionless UDP, which cannot carry an HTTP exchange, and SOCK_RAW and SOCK_SEQPACKET do not match a standard TCP HTTP client.
These are 15 of the 45 questions in the full PCPP-32-101 pack.
Get All 45 QuestionsGet all 45 questions & answers
Full access options for Python Institute PCPP-32-101
Self-study
PDF Version
- 45 actual exam questions
- Compatible with all devices
- Printable PDF format
- No download limits
- 90 days free updates
- 24/7 customer support
Best value
Bundle Pack
- Discounted PDF + online access
- 45 actual exam questions
- Both PDF and online practice test
- Free 90 days updates
- No download or practice limits
- 24/7 customer support
Exam simulation
Online Practice Test
- 45 actual exam questions
- Actual exam environment
- 90 days free updates
- Browser-based software
- 24/7 customer support
100% Money Back Guarantee
Your success comes first
At DumpsProvider, we give you a 100% money back guarantee on all of our exam dumps. For us, your success is the #1 priority and we are more than confident that our exam material will help you pass the PCPP-32-101 Exam (PCPP1 - Certified Professional in Python Programming 1) on your very first attempt.
In a rare case, if you fail your exam, we will refund your amount without asking a single question.