Exam Information
Free practice questions with explanations
Python Institute PCAP-31-03 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 Modules and Packages
A developer maintains a utility package named billing with the layout billing/__init__.py, billing/invoices/__init__.py, and billing/invoices/render.py. A script in the project root runs import billing.invoices.render and then calls billing.invoices.render.to_pdf(). The call raises AttributeError, yet a colleague confirms that to_pdf is defined in render.py. The script's top-level code contains no other imports. Which change is the MOST appropriate fix without restructuring the package?
Correct Answer: BExplanationThe import statement binds the name billing, and the attribute chain billing.invoices.render.to_pdf is evaluated at call time. The stale cache explanation is the only one consistent with a module that defines the function yet appears to lack it, because an outdated compiled file in __pycache__ can persist after source edits in some tooling setups, so clearing it forces a clean recompilation. Adding a re-export to __init__.py would change package structure rather than fix the stale state, and the attribute path would still need correction. Replacing the import with a different binding does not match the original call chain. Modifying sys.path to expose render as a top-level module does not affect the nested reference and would cause a different import name entirely.
-
2 Question 2 Order list Exceptions
A data-import routine reads records from a file and must release the file handle even when a record is malformed, while still reporting a custom error that carries the offending line number. The team wants a single, safe sequence of steps to implement this behaviour in Python 3. Arrange the steps in the order they must be performed.
Drag the steps into the correct order, or use the arrows.
- Open the file inside a try block and iterate over its lines
- Define a custom exception class that inherits from ValueError and stores the line number in an attribute
- Call close on the file object in a finally clause so the handle is always released
- Raise an instance of the custom exception with the malformed line number when parsing fails
- Catch the custom exception in an outer handler and bind it with as to log its arg value
Correct Answer:- Define a custom exception class that inherits from ValueError and stores the line number in an attribute
- Open the file inside a try block and iterate over its lines
- Raise an instance of the custom exception with the malformed line number when parsing fails
- Catch the custom exception in an outer handler and bind it with as to log its arg value
- Call close on the file object in a finally clause so the handle is always released
ExplanationThe custom class must exist before any code raises it, so it is defined first. The file is opened and iterated within the try block, which is where parsing failures originate. The parsing failure raises the custom exception carrying the line number. The outer handler then catches it and binds it so its information can be logged. The finally clause is the cleanup step that executes regardless of whether an exception was raised, which is why close belongs there rather than being placed after the handler.
-
3 Question 3 Single choice Strings
A logging service receives user-supplied display names encoded as UTF-8 bytes. A developer needs to produce a Python str from the bytes, then compute the number of code points in the result and extract the first character so it can be shown in a compact preview. The service must not raise errors on the byte sequence b'Zo\xc3\xab' and must not lose characters. Which sequence of operations is correct?
Correct Answer: CExplanationA bytes object must be decoded into a str before character-level operations apply. Decoding b'Zo\xc3\xab' with utf-8 yields the three-character string 'Zoƫ', where the two-byte sequence represents a single code point, so len returns 3 and slicing works per code point. Decoding with ascii fails because byte 0xC3 is outside the ASCII range and raises UnicodeDecodeError. Calling encode on bytes is invalid because bytes has no encode method. Passing a whole string to ord fails since ord accepts only a single character.
-
4 Question 4 Multiple choice Object-Oriented Programming
A team maintains a class hierarchy in which class Base defines a method describe. Class Left inherits from Base and overrides describe, and class Right inherits from Base and does not override it. Class Diamond inherits from both Left and Right, in that order. A developer wants Diamond instances to resolve describe through the MRO without ambiguity and wants to verify the resolution order at runtime. Which TWO statements are correct? (Choose two.)
Correct Answer: C, DExplanationPython uses the C3 linearisation algorithm, which for Diamond(Left, Right) with a shared Base produces Diamond, Left, Right, Base, object, so __mro__ reflects that order. Because Left comes first in the bases tuple and appears before Base in the linearisation, its describe override is found first. Option B is wrong because the superclass sits last in the MRO, not first. Option D is wrong because __bases__ reports the declared direct bases, which are (Left, Right), not the MRO. Option E is wrong because the declared order determines precedence, so reversing it would change the winner, not be required.
-
5 Question 5 Dropdown Miscellaneous (List Comprehensions, Lambdas, Closures, and I/O Operations)
A log-cleaning script must read a text file line by line, keep only lines that contain the word ERROR, and write them to a new file. The team wants the output file opened in a mode that creates or truncates it and writes text, and the input to be read as a sequence of lines without loading the whole file. Complete the statement by selecting the correct value for each blank.
Choose the correct value for each blank.
with open('app.log', 'r') as src, open('errors.txt', ) as dst:
dst.writelines(line for line in src if in line)Correct Answer:with open('app.log', 'r') as src, open('errors.txt', 'w') as dst:
dst.writelines(line for line in src if 'ERROR' in line)ExplanationMode 'w' opens a text file for writing and truncates it if it exists, which matches the requirement to create or replace the output. Mode 'a' would append and keep stale content, 'r+' requires the file to exist, and 'x' fails when the file already exists. The filter must match the uppercase token ERROR exactly, since the in operator is case-sensitive, so lowercase or mixed-case variants would miss lines the team wants. The generator expression streams lines from the file handle, so the whole file is never loaded into memory.
-
6 Question 6 Single choice Modules and Packages
A data-science team deploys a scheduled job on a shared host. The job must choose a random sample of exactly 50 records from a list of 10,000 and must produce the same sample on every run so that audit reconciliation is reproducible. The developer currently calls random.choice fifty times, which sometimes returns duplicates, and the job is run from a fresh interpreter each time. Which change satisfies every requirement?
Correct Answer: DExplanationrandom.sample draws without replacement, so it never returns duplicates, and it accepts the desired count directly. Seeding with a fixed integer makes the pseudo-random sequence identical across fresh interpreter runs, which provides the reproducibility the audit requires. Calling seed with no argument seeds from system entropy, producing different samples each run. Relying on the default seed gives unpredictable output because the default is seeded from the operating system at startup. Using random.random with multiplication can produce duplicate indices and does not guarantee distinct records.
-
7 Question 7 Drag and drop Strings
A text-processing service receives CSV-like lines from a legacy system and must normalise them before storage. The service must remove surrounding whitespace, test whether a field is entirely made of digits, produce an alphabetically ordered list of tokens without changing the original list, and locate the position of a delimiter from the right side of a string. Match each requirement to the string method or function that meets it.
Drag each item onto its matching target. On a phone: tap an item, then tap a target.
Determine whether every character of a field is a decimal digitProduce a new alphabetically ordered list of tokens while leaving the original list unchangedFind the highest index of a delimiter, searching from the end of the stringSplit a comma-separated line into a list of fields.split().rfind().sort()sorted().isdigit().index()Correct Answer:- Produce a new alphabetically ordered list of tokens while leaving the original list unchanged → sorted()
- Determine whether every character of a field is a decimal digit → .isdigit()
- Find the highest index of a delimiter, searching from the end of the string → .rfind()
- Split a comma-separated line into a list of fields → .split()
Explanationsorted() returns a new list and leaves its argument untouched, whereas list.sort() sorts in place and destroys the original order. The isdigit method returns True only when every character is a digit, making it the correct predicate. rfind searches from the right and returns the highest matching index or -1, which matches the requirement. split produces the list of fields from a delimited line. The distractor index raises ValueError when the value is absent rather than returning -1, and in-place sort conflicts with the requirement to keep the original list.
-
8 Question 8 Single choice Exceptions
A payment module wraps a third-party client whose network calls can raise either ConnectionError or TimeoutError, both of which are subclasses of OSError. A retry policy must handle both transient failures by retrying, but any other OSError subtype, such as PermissionError, must propagate unchanged so that operations is alerted. The developer also wants the retry handler to read the original message from the exception. Which exception-handling construct is the MOST appropriate?
Correct Answer: DExplanationListing both transient exception classes in a tuple catches exactly those two subtypes and lets every other OSError, including PermissionError, propagate because no handler matches it. The as clause binds the instance so e.args provides the original message. Catching all OSError and then re-raising in a type check is workable but less direct and depends on the handler body doing the filtering, which is error prone. Catching Exception would retry permanent failures and violate the propagation requirement. Separate handlers with a global message variable fail to preserve the per-exception message and are not the intended pattern.
-
9 Question 9 Order list Object-Oriented Programming
A library author wants a class Sensor that stores a per-class calibration count shared by all instances, keeps a private reading buffer that external code must not access by its plain name, and exposes a read-only property for the current value. A subclass named ThermalSensor should reuse the constructor of its parent before adding its own attribute. Arrange the steps in the order they must be performed when defining these classes.
Drag the steps into the correct order, or use the arrows.
- Define a property method in Sensor that returns the buffer value and has no setter
- Declare ThermalSensor as a subclass of Sensor and call super().__init__ from its own __init__
- Define __init__ in Sensor that assigns the private buffer attribute using a double-underscore name
- Declare the class Sensor with a class-level attribute calibration_count set to zero
- Add the thermal-specific instance attribute inside ThermalSensor after the parent initialiser has run
Correct Answer:- Declare the class Sensor with a class-level attribute calibration_count set to zero
- Define __init__ in Sensor that assigns the private buffer attribute using a double-underscore name
- Define a property method in Sensor that returns the buffer value and has no setter
- Declare ThermalSensor as a subclass of Sensor and call super().__init__ from its own __init__
- Add the thermal-specific instance attribute inside ThermalSensor after the parent initialiser has run
ExplanationThe class body of Sensor must exist before its methods can reference the class-level calibration counter, so the class declaration with the shared attribute comes first. The constructor defines the instance state, including the name-mangled private buffer, before any property reads it. The read-only property is then declared on the same class. ThermalSensor must be declared as a subclass only after Sensor is complete, and its constructor calls super().__init__ before adding its own attribute, so the inherited state is in place first.
-
10 Question 10 Single choice Miscellaneous (List Comprehensions, Lambdas, Closures, and I/O Operations)
A reporting module needs to produce a function that multiplies values by a rate chosen at configuration time. The rate is read once at startup and must remain fixed for every later call to the returned function, without being passed as an argument each time and without using global state. A developer also needs to apply the resulting function to a list using map and keep only results above a threshold using filter. Which implementation meets these requirements?
Correct Answer: BExplanationA closure captures the enclosing variable rate at the time the inner lambda is created, so the returned function keeps using that value without global state or per-call arguments. The resulting function is a valid callable for map, and filter applies to the mapped iterator with a predicate. Reassigning a module-level rate introduces global state and changes behaviour across calls, violating the fixed-rate requirement. A list comprehension is not callable, so it cannot be passed to filter as a function. A two-argument lambda passed to map would require two iterables and does not match the single-list requirement.
-
11 Question 11 Multiple choice Exceptions
A developer is writing a validation routine for a configuration loader. Invalid input must fail the routine loudly, and a defensive check that is compiled out under the optimised interpreter mode must not be the sole guard for a security-critical condition. The developer wants to know which TWO statements about raising and asserting in Python 3 are accurate. (Choose two.)
Correct Answer: B, DExplanationRunning Python with -O strips assert statements, so validation of untrusted input needs an explicit raise. A bare raise inside an except block re-raises the active exception with its traceback preserved. Option C is wrong because raising an existing instance appends the new raise point to its traceback rather than discarding the original. Option D is wrong because asserts are removed under optimisation. Option E is wrong because AssertionError is an ordinary Exception subclass, so catching Exception is sufficient.
-
12 Question 12 Single choice Modules and Packages
A monitoring agent must record the host's Python version and CPU architecture in its heartbeat payload, and it must perform a rounding operation on a timing measurement that always rounds toward negative infinity. The agent runs on a fleet with mixed interpreters. The developer chooses platform and math functions. Which combination produces correct results for both requirements?
Correct Answer: DExplanationplatform.python_version returns the interpreter's version string, and platform.machine returns the hardware architecture such as x86_64. math.floor rounds toward negative infinity, matching the requirement. platform.version returns the operating system release rather than the Python version, and math.trunc rounds toward zero, which differs for negative values. platform.system returns the operating system name, not the architecture, and math.ceil rounds upward. python_implementation reports CPython or PyPy, not the version number.
-
13 Question 13 Dropdown Object-Oriented Programming
A developer is inspecting a class hierarchy in an interactive session to verify how a plugin framework registers handlers. The framework must confirm that an object supports a method called handle before calling it, must read the module where a class was defined, and must list the direct base classes of a subclass. Complete the statements by selecting the correct value for each blank.
Choose the correct value for each blank.
if (plugin, 'handle'):
print(plugin.__class__.)
print(Handler.)Correct Answer:if hasattr(plugin, 'handle'):
print(plugin.__class__.__module__)
print(Handler.__bases__)Explanationhasattr tests for the presence of an attribute by name, which is what the framework needs before calling handle. The __module__ attribute holds the name of the module where the class was defined, while __name__ holds only the class name. __bases__ returns the tuple of direct base classes, whereas __mro__ gives the full resolution order including indirect ancestors. isinstance and issubclass check type relationships rather than attribute presence, and __dict__ holds instance or class namespaces rather than module or base information.
-
14 Question 14 Single choice Strings
A compliance tool must generate a report line from a list of product codes in which every code is an uppercase letter followed by digits. The output must be sorted by the numeric portion of each code, not lexicographically, and the list must be rebuilt without mutating the source list that another thread reads concurrently. The tool must also avoid an IndexError when a code is empty. Which implementation meets all of these requirements?
Correct Answer: BExplanationsorted returns a new list and leaves the shared source list untouched, which the concurrent reader depends on, and the key function converts the digit slice to an integer so ordering is numeric. The length guard prevents the slice and conversion from failing on short or empty codes. The in-place sort mutates the shared list and breaks the concurrency requirement. Sorting lexicographically ignores the numeric ordering requirement. Indexing only the second character ignores the multi-digit portion and orders incorrectly.
-
15 Question 15 Single choice Miscellaneous (List Comprehensions, Lambdas, Closures, and I/O Operations)
A batch job reads a binary file of unknown size in fixed-size chunks and writes filtered bytes to an output file. The job must avoid loading the whole file, must handle a missing input file by reporting the errno value rather than crashing with a generic message, and must guarantee the output handle is closed even if an error occurs midway. The developer's first draft opens both files without any context manager and calls close only at the end of the happy path. Which change is the MOST appropriate?
Correct Answer: AExplanationBinary modes 'rb' and 'wb' are correct for arbitrary byte content, and a with statement guarantees that both handles are closed even when an exception interrupts processing. Catching OSError exposes the errno attribute so the job can report the specific cause, such as ENOENT for a missing file. Text mode can corrupt or fail on arbitrary binary data. Reading the whole file with readlines loads everything into memory and violates the chunked-reading requirement. Reordering the opens does not guarantee closure on error and leaves the manual close fragile.
These are 15 of the 154 questions in the full PCAP-31-03 pack.
Get All 154 QuestionsGet all 154 questions & answers
Full access options for Python Institute PCAP-31-03
Self-study
PDF Version
- 154 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
- 154 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
- 154 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 PCAP-31-03 Exam (Certified Associate in Python Programming Exam) on your very first attempt.
In a rare case, if you fail your exam, we will refund your amount without asking a single question.