# Free PCPP-32-101 practice questions

> 10 free PCPP-32-101 practice questions with the correct answer and an explanation.

Page: https://devopscodelab.com/exams/python-pcpp-32-101/free-practice-questions/
Practice exams: https://devopscodelab.com/exams/python-pcpp-32-101/

### Question 1 of 10

A subclass of str customizes object creation:
class Upper(str):
    def __new__(cls, value):
        return super().__new__(cls, value.upper())
    def __init__(self, value):
        self.original = value
u = Upper('abc')
print(u, u.original, isinstance(u, str), u + 'd')
What is printed?

- A. ABC abc False ABCd
- B. ABC abc True ABCd
- C. ABC None True ABCd
- D. TypeError raised by __init__()

**Answer:** B

**Explanation:** str is immutable, so its value must be chosen in __new__, which here creates the string from value.upper(). __init__ then receives the same original argument and stores it unchanged in an instance attribute; overriding __init__ with an extra parameter is allowed because __new__ already consumed the value. Concatenation uses str.__add__, which returns a plain str built from the uppercase value and 'd', and an instance of a str subclass still passes isinstance(u, str).

### Question 2 of 10

A decorator factory is applied to a function:
def repeat(n):
    def deco(f):
        def wrapper(*args, **kwargs):
            return [f(*args, **kwargs) for _ in range(n)]
        return wrapper
    return deco
@repeat(3)
def greet(x):
    return x.upper()
print(greet('hi'), greet.__name__)
What is printed?

- A. ['HI', 'HI', 'HI'] deco
- B. ['HI', 'HI', 'HI'] greet
- C. ['HI', 'HI', 'HI'] wrapper
- D. ['HI'] wrapper

**Answer:** C

**Explanation:** repeat(3) returns deco, deco(greet) returns wrapper, so the name greet is bound to wrapper, which returns a list of three results. Because functools.wraps was not used, the __name__ of the decorated object is 'wrapper', not 'greet'. 'deco' is the name of the intermediate decorator that is discarded after decoration, and n=3 makes the list comprehension call the original function three times, not once.

### Question 3 of 10

A base class registers its subclasses:
class Plugin:
    registry = {}
    def __init_subclass__(cls, key=None, **kwargs):
        super().__init_subclass__(**kwargs)
        Plugin.registry[key or cls.__name__.lower()] = cls
class Csv(Plugin, key='csv'):
    pass
class Json(Plugin):
    pass
print(sorted(Plugin.registry), 'plugin' in Plugin.registry)
What is printed?

- A. ['csv', 'json'] False
- B. [] False
- C. ['csv'] False
- D. ['csv', 'json', 'plugin'] True

**Answer:** A

**Explanation:** __init_subclass__ runs each time a subclass is created, receiving extra keyword arguments from the class statement, so Csv registers under 'csv' and Json under its lowercased name. It does not run for the class that defines it, so Plugin itself is not registered. Json is registered too, because key defaults to None and the class name is used. Registration happens at class creation, without any instance being made.

### Question 4 of 10

Consider the following class hierarchy:
class A:
    def who(self): return 'A'
class B(A):
    def who(self): return 'B' + super().who()
class C(A):
    def who(self): return 'C' + super().who()
class D(B, C):
    def who(self): return 'D' + super().who()
print(D().who(), [k.__name__ for k in D.__mro__])
What is the output?

- A. DBCA ['D', 'B', 'C', 'A', 'object']
- B. DBACA ['D', 'B', 'A', 'C', 'object']
- C. DBA ['D', 'B', 'A', 'C', 'object']
- D. DCBA ['D', 'C', 'B', 'A', 'object']

**Answer:** A

**Explanation:** Python linearizes the diamond with C3, giving the MRO D, B, C, A, object, and each super().who() call moves to the next class in that order, so the chain builds 'DBCA'. A depth-first order (D, B, A, C) is what classic old-style classes used and would visit A before C. Listing C before B ignores the left-to-right order of the bases, and A is never visited twice because C3 keeps each class only once.

### Question 5 of 10

A long arithmetic expression must be split over several lines. Following the current PEP 8 recommendation for new code, where should the lines break relative to binary operators such as + and -?

- A. After each binary operator, so every broken line ends with the operator
- B. Only after commas, because PEP 8 forbids breaking a line next to any binary operator
- C. Either way, as long as each operator also gets its own line with no operands
- D. Before each binary operator, so every continued line starts with the operator

**Answer:** D

**Explanation:** PEP 8 recommends breaking before binary operators in new code, following Knuth's style, because the operators then line up with their operands and the expression is easier to read. Breaking after operators is still allowed for consistency with existing code, but it is not the recommendation, and PEP 8 does not forbid operator breaks or require operators on lines of their own.

### Question 6 of 10

A tkinter developer places one Label in a Frame with pack() and a second Label in the same Frame with grid(). The application freezes or raises a TclError. What is the recommended fix?

- A. Use only one geometry manager for all widgets that share the same master
- B. Give the gridded Label a higher row number so pack() can place the other Label
- C. Call update_idletasks() between the calls so that both managers can share it
- D. Call grid() before pack() so that the grid manager takes priority in the Frame

**Answer:** A

**Explanation:** pack() and grid() both try to control the size of their shared master, and when used for siblings in the same container they can fight endlessly; recent Tk versions detect this and raise a TclError. The fix is to use one manager per container, nesting Frames if different layouts are needed. Changing call order, forcing idle updates or choosing row numbers does not stop the two managers from conflicting.

### Question 7 of 10 (choose 2)

A trainee asks how event-driven GUI programs differ from simple scripts. Which two statements are correct for tkinter applications? (Choose two.)

- A. Handlers run in the order in which the widgets were created, regardless of the events
- B. The event loop dispatches events such as clicks, key presses and timers to the bound handlers
- C. Widgets can be updated safely from any thread without any coordination with the loop
- D. Handlers should return quickly and split long work into after() steps or worker threads
- E. The program polls each widget in its own loop to find out whether it has been clicked

**Answer:** B, D

**Explanation:** In event-driven programs the event loop waits for events and calls the matching handlers, so the program flow follows user actions. A slow handler blocks that loop, so long tasks are split or moved to threads that hand results back. Applications do not poll widgets themselves, handlers run when their events occur, and tkinter is not safe to update freely from other threads.

### Question 8 of 10

A dictionary is serialized before being sent to a REST service:
import json
print(json.dumps({'a': None, 'b': (1, 2), 3: True}))
What is the output?

- A. {"a": null, "b": {"0": 1, "1": 2}, "3": true}
- B. TypeError: keys must be str, int, float, bool or None
- C. {"a": null, "b": [1, 2], "3": true}
- D. {"a": None, "b": [1, 2], "3": True}

**Answer:** C

**Explanation:** json.dumps() converts None to null, True to true and tuples to JSON arrays, and it converts integer keys to strings because JSON object keys are always strings. Python literals such as None and True are not valid JSON. A tuple is encoded as an array, not as an object keyed by index, and the TypeError about keys is raised only for key types such as tuples, not for ints.

### Question 9 of 10

A client sends 'GET / HTTP/1.1' with a Host header over a raw socket and then reads with a loop that stops when recv() returns b''. The full page arrives, but the loop never ends. What is the most likely fix?

- A. Call sock.listen() after sending, so the client is notified when the response is done
- B. Increase the recv() buffer to 64 KB, so the whole response arrives in one single call
- C. Send the request as a str instead of bytes, so the server knows where the request ends
- D. Add a Connection: close header, so the server closes the connection after its response

**Answer:** D

**Explanation:** HTTP/1.1 connections are persistent by default, so the server keeps the socket open after responding and recv() blocks instead of returning b''. Requesting Connection: close makes the server close the connection, which ends the loop. Sockets only accept bytes, listen() is a server call, and a larger buffer does not change when the peer closes the stream.

### Question 10 of 10

A setup script creates a table with CREATE TABLE products(...). It works the first time, but running it again stops with sqlite3.OperationalError: table products already exists. Which change lets the script run repeatedly while keeping existing data?

- A. Open the connection with sqlite3.connect('shop.db', uri=True)
- B. Call con.rollback() before executing the CREATE TABLE statement
- C. Run DROP TABLE products before every CREATE TABLE statement
- D. Use CREATE TABLE IF NOT EXISTS products(...) in the setup script

**Answer:** D

**Explanation:** IF NOT EXISTS makes the statement a no-op when the table is already present, so existing rows stay intact. Dropping the table first also avoids the error but deletes all data every run. The uri flag only changes how the database name is parsed, and rolling back does not remove a table that was already committed.

Ready for a timed run? Take the free 15-question PCPP-32-101 mini exam: https://devopscodelab.com/app/exams/python-pcpp-32-101/mini/

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