PCAP-31-04
Free PCAP-31-04 practice questions
10 questions from our PCAP-31-04 practice tests, each with the correct answer and a written explanation. Read them with the answers shown, or switch to quiz mode and answer first.
Question 1 of 10, Modules and Packages. Choose 2.
A team wants reproducible environments for a Python service. Which two pip practices directly support this goal? (Choose two.)
- AUse 'pip show' on the build server to decide which versions to install at deploy time
- BRun 'pip install --upgrade' on every package before each deployment to stay current
- CRecreate the environment elsewhere with 'pip install -r requirements.txt' Correct answer
- DGenerate a pinned list with 'pip freeze > requirements.txt' and commit it with the code Correct answer
- EInstall packages globally with 'pip install --user' so that every project shares them
Answer and explanation: pip freeze writes the exact installed versions in requirement-specifier form, and installing from that file with -r rebuilds the same set of versions on another machine. Upgrading everything before each deployment pulls whatever is newest and breaks reproducibility, a shared --user install mixes dependencies between projects, and pip show only displays metadata for an installed package rather than defining what should be installed.
Question 2 of 10, Exceptions. Choose 2.
A developer defines a custom exception for an inventory module. Which two practices are recommended? (Choose two.)
- AName the class without the Error suffix so it cannot be confused with built-in exception classes
- BDerive the class from Exception or from a more specific built-in exception rather than from BaseException Correct answer
- CRaise the class itself with a string, as in 'raise InventoryError, "low stock"', to attach a message
- DGroup related errors under a common base class, such as InventoryError, so callers can catch them together Correct answer
- EDerive the class from BaseException so that a bare 'except Exception' clause cannot intercept it
Answer and explanation: Application exceptions should inherit from Exception (or a specific built-in subclass) and are commonly organised under a shared base class so callers can handle the whole family. Deriving from BaseException puts the class alongside SystemExit and KeyboardInterrupt and makes it escape normal handlers, which is not the intent. The Error suffix is the standard naming convention, and the comma raise syntax is Python 2 and a SyntaxError in Python 3.
Question 3 of 10, Strings
A path-cleaning helper strips characters from the ends of a string: a = '//report.txt/'.strip('/') b = 'data/report.txt'.rstrip('.txt') print(a + '|' + b) What is printed?
- Areport.txt|data/report
- Breport.txt|data/repor Correct answer
- Creport|data/report
- Dreport.txt|data/report.txt
Answer and explanation: strip() and its variants treat the argument as a set of characters, not as a substring. strip('/') removes slashes from both ends of the first string. rstrip('.txt') keeps removing trailing characters while they are '.', 't' or 'x', so after '.txt' it also removes the final 't' of 'report' and stops at 'r', leaving 'data/repor'. To remove an exact suffix, use removesuffix('.txt').
Question 4 of 10, Object-Oriented Programming
A developer tries to define a class whose MRO cannot be linearised: class X: pass class Y(X): pass class Z(X, Y): pass What happens?
- AA TypeError is raised only when a Z instance is first created
- BZ is created with the MRO Z, X, Y, object
- CA TypeError is raised when the class statement for Z is executed Correct answer
- DZ is created with the MRO Z, Y, X, object
Answer and explanation: Y inherits from X, so X must come after Y in any valid MRO, but listing X before Y in Z's bases demands the opposite. C3 linearisation cannot satisfy both orders, so Python raises TypeError ('Cannot create a consistent method resolution order') as soon as the class statement runs. The error is not deferred to instantiation, and Python does not silently reorder the bases.
Question 5 of 10, Object-Oriented Programming
A developer combines class and instance namespaces of a hierarchy: class Base: kind = 'base' def greet(self): return self.kind class Child(Base): kind = 'child' def __init__(self): self.limit = 3 c = Child() print(list(vars(c)), [k for k in Child.__dict__ if not k.startswith('__')], c.greet()) What is printed?
- A['limit'] ['kind'] child Correct answer
- B['limit', 'kind'] ['greet'] child
- C[] ['kind', 'limit'] base
- D['limit'] ['kind'] base
Answer and explanation: The instance __dict__ contains only limit, assigned in __init__. Child.__dict__ holds the class variable kind defined in its body (dunder entries are filtered out), while the inherited greet() method stays in Base.__dict__ and class variables never appear in the instance's own dictionary. greet() reads self.kind, which finds Child's value 'child' first in the MRO.
Question 6 of 10, Object-Oriented Programming
A developer checks the MRO of a class that has a diamond hierarchy with an extra level: class A: pass class B(A): pass class C(B): pass class D(A): pass class E(C, D): pass print(' '.join(k.__name__ for k in E.__mro__[:-1])) What is printed?
- AE D C B A
- BE C B D A Correct answer
- CE C D B A
- DE C B A D
Answer and explanation: C3 linearisation merges the MROs of the bases, C, B, A and D, A, in the left-to-right order of E's bases. After E and C it takes B, the next head that appears in no other list's tail; A cannot follow yet because it is still in the tail of D's list, so D comes next and A last. A depth-first order would visit A before D, and putting D before B ignores that B is reached first through C.
Question 7 of 10, Advanced Python Constructs and I/O
What is the output of the following code? pairs = [(2, 'plum'), (3, 'apple'), (1, 'kiwi')] print([n for n, name in sorted(pairs, key=lambda p: p[1])])
- A[2, 1, 3]
- B[3, 1, 2] Correct answer
- C[1, 2, 3]
- D[3, 2, 1]
Answer and explanation: The key function returns each tuple's second element, so sorted() orders the tuples alphabetically by fruit name: apple, kiwi, plum. The comprehension then extracts the number from each tuple, giving 3, 1, 2. Ascending numbers would result from sorting by the first element, and the other orders are the original or a reversed sequence, neither of which the code requests.
Question 8 of 10, Advanced Python Constructs and I/O
What is the output of the following code? command = ['resize', 800, 600] match command: case ['resize', w]: print('resize', w) case ['resize', w, h]: print('resize', w, h) case _: print('fallback')
- Aresize 800 600 Correct answer
- Bfallback
- Cresize 800
- Dresize 600
Answer and explanation: Case patterns are tried top to bottom and the first match wins. The list has three elements, so the two-element pattern fails, while the three-element pattern matches and binds w and h. A sequence pattern matches lists as well as tuples, so the wildcard fallback is not reached, and binding only one of the two numbers would require a two-element pattern to match.
Question 9 of 10, Advanced Python Constructs and I/O
What is the output of the following code? data = bytearray(b'hello') data[0] = 72 print(data)
- Ab'Hello'
- Bbytearray(b'Hello') Correct answer
- CTypeError
- Dbytearray(b'72ello')
Answer and explanation: Unlike bytes, a bytearray is mutable, so an element can be replaced by an integer between 0 and 255. Assigning 72 (the code for 'H') to index 0 changes the first byte, and the repr shows it as the character H rather than the number. The object stays a bytearray, so the plain bytes repr is not printed. The same assignment on a bytes object would raise TypeError.
Question 10 of 10, Testing, Debugging, Collaborative Development, and AI Assistance
A developer runs a script and receives a traceback that ends with the line 'ZeroDivisionError: division by zero'. In which part of the traceback is the line of code that actually raised the exception shown?
- AIn the frame of the module-level code, because exceptions are always reported there
- BIn a separate section printed after the exception message at the end of the output
- CIn the last frame listed, directly above the exception type and message Correct answer
- DIn the first frame listed, directly below the 'Traceback (most recent call last)' header
Answer and explanation: Python prints tracebacks with the most recent call last, so the frame closest to the final error line is where the exception was raised. The first frame is usually the outermost caller, such as the module-level code that started the call chain. Nothing is printed after the exception message, and the raising frame is often inside a function rather than at module level.