# Free PCAP-31-04 practice questions

> 10 free PCAP-31-04 practice questions with the correct answer and an explanation.

Page: https://devopscodelab.com/exams/pcap-python-associate/free-practice-questions/
Practice exams: https://devopscodelab.com/exams/pcap-python-associate/

### Question 1 of 10 (choose 2)

A team wants reproducible environments for a Python service. Which two pip practices directly support this goal? (Choose two.)

- A. Use 'pip show' on the build server to decide which versions to install at deploy time
- B. Run 'pip install --upgrade' on every package before each deployment to stay current
- C. Recreate the environment elsewhere with 'pip install -r requirements.txt'
- D. Generate a pinned list with 'pip freeze > requirements.txt' and commit it with the code
- E. Install packages globally with 'pip install --user' so that every project shares them

**Answer:** C, D

**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 (choose 2)

A developer defines a custom exception for an inventory module. Which two practices are recommended? (Choose two.)

- A. Name the class without the Error suffix so it cannot be confused with built-in exception classes
- B. Derive the class from Exception or from a more specific built-in exception rather than from BaseException
- C. Raise the class itself with a string, as in 'raise InventoryError, "low stock"', to attach a message
- D. Group related errors under a common base class, such as InventoryError, so callers can catch them together
- E. Derive the class from BaseException so that a bare 'except Exception' clause cannot intercept it

**Answer:** B, D

**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

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?

- A. report.txt|data/report
- B. report.txt|data/repor
- C. report|data/report
- D. report.txt|data/report.txt

**Answer:** B

**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

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?

- A. A TypeError is raised only when a Z instance is first created
- B. Z is created with the MRO Z, X, Y, object
- C. A TypeError is raised when the class statement for Z is executed
- D. Z is created with the MRO Z, Y, X, object

**Answer:** C

**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

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
- B. ['limit', 'kind'] ['greet'] child
- C. [] ['kind', 'limit'] base
- D. ['limit'] ['kind'] base

**Answer:** A

**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

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?

- A. E D C B A
- B. E C B D A
- C. E C D B A
- D. E C B A D

**Answer:** B

**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

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]
- C. [1, 2, 3]
- D. [3, 2, 1]

**Answer:** B

**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

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')

- A. resize 800 600
- B. fallback
- C. resize 800
- D. resize 600

**Answer:** A

**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

What is the output of the following code?
data = bytearray(b'hello')
data[0] = 72
print(data)

- A. b'Hello'
- B. bytearray(b'Hello')
- C. TypeError
- D. bytearray(b'72ello')

**Answer:** B

**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

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?

- A. In the frame of the module-level code, because exceptions are always reported there
- B. In a separate section printed after the exception message at the end of the output
- C. In the last frame listed, directly above the exception type and message
- D. In the first frame listed, directly below the 'Traceback (most recent call last)' header

**Answer:** C

**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.

Ready for a timed run? Take the free 15-question PCAP-31-04 mini exam: https://devopscodelab.com/app/exams/pcap-python-associate/mini/

DevOpsCode Lab is not affiliated with Python Institute. PCAP-31-04 and related names are trademarks of their owners. We write every question ourselves; these are not real exam questions.
