Courseiva

Python Institute Certified Professional in Python Programming 1 (PCPP1, PCPP-32-101) (PCPP1) (PCPP1) — Questions 226–290

290 questions total · 4 pages · All types, answers revealed

Page 3

Page 4 of 4

226
MCQhard

You are designing a REST client that must call an endpoint protected by OAuth 2.0 using the client credentials grant. The authorization server expects the client identifier and client secret to be sent in the request body as `application/x-www-form-urlencoded`, along with `grant_type=client_credentials`. Which `requests` call correctly obtains the token?

A.requests.post(token_url, data={'grant_type': 'client_credentials', 'client_id': cid, 'client_secret': secret})
B.requests.post(token_url, json={'grant_type': 'client_credentials', 'client_id': cid, 'client_secret': secret})
C.requests.post(token_url, auth=(cid, secret), data={'grant_type': 'client_credentials'})
D.requests.get(token_url, params={'grant_type': 'client_credentials', 'client_id': cid, 'client_secret': secret})
AnswerA

The data parameter encodes the dictionary as application/x-www-form-urlencoded, which is exactly what the OAuth 2.0 token endpoint expects for the client credentials grant. Including grant_type, client_id, and client_secret in the body matches the server requirement described in the scenario.

Why this answer

OAuth 2.0 token requests use POST with application/x-www-form-urlencoded bodies. The data parameter in requests performs that encoding automatically. Sending the grant type and client credentials in the body, rather than as Basic auth or JSON, satisfies the server's stated expectations and returns the access token needed for subsequent API calls.

Exam trap

The trap here is conflating HTTP Basic authentication with OAuth 2.0 client authentication and assuming JSON is universally accepted by token endpoints.

227
MCQmedium

In a Tkinter grid layout, you want a button to span across two columns. Which parameter should you use?

A.columnspan=2
B.span_cols=2
C.merge=2
D.cols=2
AnswerA

columnspan=2 instructs Tkinter's grid geometry manager to allocate two adjacent column cells to the widget, satisfying the stem's requirement that the button span two columns. The parameter is passed directly to grid(), and Tkinter merges the specified cells horizontally without altering other widgets' placements.

Why this answer

The columnspan parameter in the grid() method manager allows a widget to occupy multiple columns.

228
MCQmedium

You are implementing the Observer pattern. Why should you avoid using a strong reference to the observers in the subject's list?

A.It causes circular dependency issues.
B.It makes the notify method thread-unsafe.
C.It violates the principle of encapsulation.
D.It prevents the observer from being garbage collected when it is no longer needed.
AnswerD

A strong reference held by the subject keeps each observer alive, so reference counting never reaches zero and the garbage collector cannot reclaim observers that are no longer needed. Weak references let them be collected once external references disappear.

Why this answer

Strong references prevent garbage collection of the observers, leading to memory leaks if observers are meant to be temporary.

229
MCQeasy

What is the primary difference between @classmethod and @staticmethod?

A.@staticmethod can access instance variables.
B.@classmethod receives the class as the first argument; @staticmethod does not.
C.@classmethod is for private methods.
D.@classmethod is slower.
AnswerB

A classmethod binds to the class and passes it implicitly as the first argument (conventionally `cls`), so it can access or modify class state and works correctly with inheritance. A staticmethod receives no implicit first argument, behaving as a plain function namespaced inside the class. This directly satisfies the stem's request for the primary distinction.

Why this answer

@classmethod receives the class as the first argument, while @staticmethod receives no implicit class or instance argument.

230
MCQeasy

What is the correct way to specify the title of a Tkinter window?

A.root.set_title('My App')
B.root.title('My App')
C.root.name = 'My App'
D.root.set_header('My App')
AnswerB

The Tk root window exposes title() as its method for setting the caption shown in the window manager's title bar, so root.title('My App') sets it directly. Assigning to a title attribute would not update the displayed caption.

Why this answer

Tkinter's Tk and Toplevel widget classes expose the title() method, which is the canonical API for setting the window manager caption. Calling root.title('My App') sets the WM_NAME property on the underlying X11/Win32 window, which the OS window manager renders in the title bar. There is no set_title() method on Tkinter widgets, so option A would raise an AttributeError at runtime.

Exam trap

The trap here is that candidates familiar with other GUI frameworks (Qt's setWindowTitle, Java Swing's setTitle, wxPython's SetTitle) assume Tkinter follows the same set_* naming convention, but Tkinter uses the terse title() method instead.

How to eliminate wrong answers

Option A is wrong because Tkinter widgets do not expose a set_title() method; the correct API is title(), and calling set_title() raises AttributeError. Option C is wrong because assigning root.name = 'My App' merely creates an arbitrary Python instance attribute on the Tk object and has no effect on the window manager caption. Option D is wrong because set_header() is not a Tkinter method at all — it does not exist on Tk, Toplevel, or any widget class, so it would raise AttributeError.

231
Multi-Selectmedium

Which THREE of the following are valid ways to configure a widget's appearance after it has been created?

Select 3 answers
A.widget['bg'] = 'blue'
B.widget.config(bg='blue')
C.widget.configure(bg='blue')
D.widget.set_bg('blue')
E.widget.style = 'blue'
AnswersA, B, C

Assigning to `widget['bg']` uses Tkinter's item-configuration protocol, routing the value to the widget's `configure()` method for the `bg` option. This mutates the existing widget's background colour in place, satisfying the stem's requirement that appearance be changed after creation rather than at construction.

Why this answer

Option A, widget['bg'] = 'blue', is correct because Tkinter widgets implement the mapping protocol for configuration, so assigning to a widget's option key via item assignment updates that option just like a configuration call. Option B, widget.config(bg='blue'), is correct because config() is the standard Tkinter method for changing one or more widget options after creation, and bg is a valid option name. Option C, widget.configure(bg='blue'), is correct because configure() is simply the full-name alias of config() and performs the identical option-setting operation.

Option D is not a valid Tkinter API, since there is no set_bg() method on widgets, and option E is incorrect because style is not a generic widget option that accepts a color string; styling is handled through ttk styles or specific options like bg.

232
MCQmedium

You are building a desktop tool with tkinter. A user clicks a button, and while a long file-compression routine runs you want a small window with a progress bar to stay visible and animated; the main application window must remain responsive to the user's clicks throughout. Which approach should you use?

A.Instantiate a second Tk() root, place the progress bar in it, and call its mainloop() from the callback.
B.Run the compression loop inside the button's command callback and call update_idletasks() after each chunk is processed.
C.Create a tkinter.Toplevel window for the progress bar and run the compression in a separate thread that posts status updates back to the main thread.
D.Call mainloop() a second time from inside the button's command callback so the progress window gets its own event loop.
AnswerC

Tkinter is not thread-safe, but separating the CPU-bound work onto a worker thread keeps the main thread free to service the event loop, so both windows stay responsive and the progress bar animates. The worker must not touch widgets directly; it should hand results to the main thread, for example through a queue polled with after(), which is the standard pattern for this scenario.

Why this answer

Long-running work must never execute on the thread that runs the Tk event loop. Moving the compression onto a worker thread lets the main thread keep dispatching events, so the progress window redraws and the primary window accepts clicks. Because Tkinter widgets may only be touched from the main thread, the worker communicates through a thread-safe queue that the GUI polls periodically.

Exam trap

The trap here is assuming that sprinkling update_idletasks() or update() into a blocking callback makes tkinter multithreaded or keeps the interface live.

233
MCQhard

You are building a Python script that needs to create a ZIP archive containing files from a directory. You want to preserve the directory structure inside the archive. Which approach using the zipfile module correctly adds the file '/data/reports/summary.txt' as 'reports/summary.txt' inside the archive?

A.zipf.write('/data/reports/summary.txt')
B.zipf.add('/data/reports/summary.txt', 'reports/summary.txt')
C.zipf.write('/data/reports/summary.txt', arcname='summary.txt')
D.zipf.write('/data/reports/summary.txt', arcname='reports/summary.txt')
AnswerD

The write() method's arcname parameter sets the name inside the archive. By passing 'reports/summary.txt', the file is stored with that path, preserving the desired directory structure. This is the correct way to include a file from a different absolute path while renaming it within the archive.

Why this answer

The zipfile.ZipFile.write() method accepts an arcname parameter that specifies the name of the file inside the archive. To preserve a directory structure, you provide a relative path as the arcname, such as 'reports/summary.txt'. This ensures the file is stored with that exact path, regardless of its location on the filesystem.

Exam trap

The trap here is confusing the write() method's arcname parameter with the source filename, or assuming that the source path is automatically mirrored in the archive.

234
MCQmedium

A developer is writing a function that computes the average of a list of numbers. The function should not modify the input list. Which annotation best communicates this intent and aligns with PEP 484 best practices?

A.def average(numbers: List[float]) -> float:
B.def average(numbers: Tuple[float, ...]) -> float:
C.def average(numbers: list) -> float:
D.def average(numbers: Sequence[float]) -> float:
AnswerD

Sequence[float] from typing indicates an ordered, read-only collection of floats. It communicates that the function will not mutate the input, and it accepts any sequence (list, tuple, etc.), aligning with PEP 484 and best practices for flexible, safe APIs.

Why this answer

Using Sequence[float] from the typing module communicates that the function accepts any read-only sequence of floats, preserving flexibility while indicating no mutation. This follows PEP 484 guidance to prefer abstract types for parameters. List and Tuple are more specific and imply mutability or a concrete type, which is unnecessarily limiting.

Exam trap

The trap here is assuming that a more specific type like List[float] is always better, when in fact abstract types like Sequence better express intent and improve API flexibility.

235
MCQhard

When using configparser, how do you handle multiline values?

A.Use a backslash at the end of each line.
B.Indent the subsequent lines.
C.Wrap them in triple quotes ('''...''').
D.Use the '\n' escape character.
AnswerB

ConfigParser treats indented continuation lines as part of the preceding option's value, joining them into one multiline string. Indenting subsequent lines therefore satisfies the stem's requirement, unlike blank lines or unindented text which start new keys.

Why this answer

You indent lines following the initial line within the option.

236
MCQeasy

A developer is writing a module-level variable that holds the maximum number of retries for a network client and will never change during runtime. Which naming convention does PEP 8 recommend for this constant?

A.Use CapWords, such as `MaxRetries`, to indicate that the value is a named entity.
B.Use all uppercase letters with underscores between words, such as `MAX_RETRIES`.
C.Prefix the name with a single underscore, such as `_MAX_RETRIES`, to mark it as a constant.
D.Use lowercase letters with underscores, such as `max_retries`, because Python does not enforce constantness.
AnswerB

PEP 8 recommends all uppercase letters with underscores for constants, so `MAX_RETRIES` is the correct form. This convention makes it immediately clear to readers that the value is intended to remain constant. It also distinguishes constants from regular variables, which use lowercase with underscores, improving readability across the module.

Why this answer

PEP 8 names constants using all uppercase letters with underscores separating words, so `MAX_RETRIES` is the recommended form. Python does not enforce immutability, but the naming convention communicates intent to readers and distinguishes constants from ordinary variables and classes. Other capitalizations belong to different categories of names.

Exam trap

The trap here is thinking that because Python does not enforce constantness, the all-caps convention is optional rather than a strong readability signal.

237
MCQeasy

When using sqlite3.Row, what is the primary benefit over using a standard tuple?

A.It automatically commits transactions.
B.It provides dictionary-like access to columns by name.
C.It is faster to execute.
D.It supports multi-threading natively.
AnswerB

sqlite3.Row wraps each result row so columns are addressable by name as well as index, unlike a plain tuple which only supports positional access. This satisfies the stem by removing the need to remember column order when reading query results.

Why this answer

sqlite3.Row allows accessing column values by name (string keys) instead of just numerical indices.

238
MCQeasy

Which magic method enables index access (e.g., obj[i])?

A.__getitem__
B.__index__
C.__setitem__
D.__access__
AnswerA

`__getitem__` is the magic method Python invokes for subscription syntax, so defining it lets instances respond to `obj[i]` with square brackets. It satisfies the stem's index-access constraint directly, unlike `__getattr__`, which handles attribute lookup, or `__iter__`, which drives iteration protocols.

Why this answer

The __getitem__ method allows an object to support indexing.

239
MCQeasy

Which comment style is preferred for block comments in Python?

A.Using a string literal (triple quotes) at the top level.
B.Using block comments inside a single line.
C.Each line starting with a single '#' and a space.
D.Using a single '#' at the end of every line.
AnswerC

Each line beginning with a single '#' and a space keeps every line independently commented, so no delimiter can be broken by nesting or formatting. This satisfies Python's style guidance (PEP 8) for block comments, unlike triple-quoted strings, which are string literals rather than true comments and can interfere with docstring conventions.

Why this answer

Block comments should consist of paragraphs of text, each starting with a # and a single space.

240
Multi-Selectmedium

Which TWO of the following are true about magic methods?

Select 2 answers
A.They are only available for built-in types.
B.They provide hooks into Python language operators.
C.They always start and end with '__'.
D.They cannot be overridden.
E.They are intended for direct calling by the user.
AnswersB, C

Magic methods such as __add__, __eq__ and __len__ are invoked implicitly by Python's syntax and built-in operations, letting user classes integrate with operators, iteration and context managers. This hook mechanism is exactly what the stem asks about, rather than naming conventions or inheritance behaviour.

Why this answer

Option B is correct because magic methods (also called dunder methods) act as hooks that let user-defined classes integrate with Python's built-in syntax and operators — for example, __add__ is invoked by the + operator, __len__ by len(), and __iter__ by iteration. Option C is correct because magic methods are conventionally and syntactically named with a leading and trailing double underscore, such as __init__, __str__, or __eq__. Option A is wrong because magic methods are not limited to built-in types; user-defined classes can define and override them.

Option D is wrong because magic methods can be overridden in subclasses or custom classes to customize behavior. Option E is wrong because magic methods are meant to be invoked implicitly by the interpreter through operators and built-in functions, not called directly by the user.

241
MCQhard

You are using 'concurrent.futures.ThreadPoolExecutor' to fetch data from multiple REST APIs. What happens if an exception is raised inside a thread?

A.The exception is ignored by the ThreadPoolExecutor
B.The entire program crashes immediately
C.The thread dies silently without notification
D.The exception is stored and raised when calling future.result()
AnswerD

ThreadPoolExecutor captures any exception raised inside a worker and stores it on the Future; it is not propagated in the worker thread. Calling future.result() re-raises that stored exception in the calling thread, satisfying the stem's scenario.

Why this answer

Exceptions raised in a future are captured and re-raised when calling result() on the Future object returned by submit().

242
Multi-Selectmedium

Which TWO of the following statements correctly describe the behavior of the Tkinter 'pack' geometry manager?

Select 2 answers
A.The manager automatically ignores the order in which pack() is called.
B.The 'side' parameter can be set to 'top', 'bottom', 'left', or 'right'.
C.Widgets are placed in a grid coordinate system.
D.Widgets are positioned at exact X and Y coordinates.
E.The 'fill' parameter can be set to 'x', 'y', 'both', or 'none'.
AnswersB, E

The side parameter accepts exactly these four cardinal values, anchoring the widget against that edge of the parent container and allocating the remaining cavity to subsequent widgets. This matches the stem's request for a correct description of pack's placement behaviour.

Why this answer

Option B is correct because pack()'s 'side' parameter accepts exactly the four values 'top', 'bottom', 'left', and 'right', which determine the edge of the container against which the widget is packed (defaulting to 'top'). Option E is correct because the 'fill' parameter accepts 'x', 'y', 'both', or 'none', controlling whether the widget stretches to fill available space along the horizontal axis, vertical axis, both, or neither. Option A is wrong because pack() honors call order: widgets are allocated space in the sequence pack() is invoked, so order directly affects layout.

Option C is wrong because the grid coordinate system belongs to the grid() geometry manager, not pack(). Option D is wrong because absolute X/Y positioning is the domain of the place() geometry manager, whereas pack() uses relative cavity-based allocation.

Exam trap

PCPP1 often tests whether candidates confuse the three Tkinter geometry managers — pack(), grid(), and place() — attributing grid coordinates or absolute positioning to pack().

243
Multi-Selecthard

Which THREE of the following are valid ways to pass arguments to a function called by a Tkinter button command?

Select 3 answers
A.command=lambda arg=arg1: my_func(arg)
B.command=lambda: my_func(arg1)
C.command=functools.partial(my_func, arg1)
D.command=my_func(arg1=value)
E.command=my_func(arg1)
AnswersA, B, C

The lambda captures arg1 as a default parameter at definition time, so each button's callback binds its own value rather than the loop variable's final state. This is the standard Tkinter pattern for passing arguments to command callbacks.

Why this answer

Option A is correct because a lambda with a default argument (arg=arg1) captures the value at definition time and passes it to my_func when the button is clicked, avoiding late-binding issues. Option B is correct because a zero-argument lambda that closes over arg1 defers execution of my_func(arg1) until the button is pressed, which is the standard Tkinter pattern for passing arguments. Option C is correct because functools.partial(my_func, arg1) creates a callable that already has arg1 bound, and Tkinter accepts any callable as the command.

Option D is wrong because my_func(arg1=value) is invoked immediately at widget creation, so command receives the function's return value rather than a callable. Option E is wrong for the same reason: my_func(arg1) executes right away and its result is assigned to command, not deferred until the button is clicked.

244
MCQmedium

You are configuring a logging FileHandler. What does the 'mode' parameter control?

A.The log format.
B.The rotation interval.
C.The file opening mode.
D.The character encoding.
AnswerC

The mode parameter is passed straight to the built-in open() call, so it sets the file opening mode such as 'a' for append or 'w' for overwrite. This governs whether existing log content is preserved or truncated.

Why this answer

The 'mode' parameter controls the file opening mode (e.g., 'a' for append, 'w' for write).

245
Multi-Selecthard

Which TWO of the following statements about the Python 'requests' library are correct?

Select 2 answers
A.It uses 'urllib3' internally for connection pooling
B.It does not support HTTPS
C.It is part of the standard library
D.It is thread-safe by default for all operations
E.It automatically closes connections for every request if not using a Session
AnswersA, E

Leveraging 'urllib3' beneath its API, 'requests' reuses TCP connections through pooling, avoiding a fresh handshake per call. This satisfies the stem's requirement for a true statement about the library's internals, since connection reuse is genuinely delegated to that lower-level dependency.

Why this answer

Option A is correct because the requests library is built on top of urllib3, which provides the underlying connection pooling and HTTP transport capabilities. Option E is correct because when you call requests.get() or similar top-level functions without using a Session object, requests creates a temporary Session internally, performs the request, and then closes the connection rather than reusing it. Option B is incorrect because requests fully supports HTTPS and TLS/SSL verification.

Option C is incorrect because requests is a third-party package that must be installed via pip, not part of the Python standard library. Option D is incorrect because requests is not guaranteed thread-safe for all operations; while Session objects can be used across threads with care, the library does not provide blanket thread-safety guarantees.

246
Multi-Selectmedium

Which TWO of the following are valid ways to create a singleton in Python?

Select 2 answers
A.Using a global variable that is not initialized.
B.Using a function that returns a new instance every call.
C.Using a base class with a custom __new__ method.
D.Using a standard class without any special methods.
E.Using a module as a singleton.
AnswersC, E

Overriding `__new__` in a base class lets you intercept instantiation before `__init__` runs, returning the same cached instance on every call. This satisfies the singleton constraint by centralising instance control in one reusable parent, so subclasses inherit the behaviour without duplicating logic.

Why this answer

Option C is correct because overriding __new__ in a base class lets you intercept instance creation and return the same cached instance every time, which is the canonical Python idiom for enforcing a single instance. Option E is correct because Python modules are imported only once and cached in sys.modules, so module-level state and functions naturally behave as a singleton. Option A is wrong because an uninitialized global variable provides no instance at all and no control over creation.

Option B is wrong because returning a new instance on every call is the opposite of the singleton pattern. Option D is wrong because a plain class with no special methods creates a fresh object on each instantiation.

247
MCQeasy

Which widget is most suitable for displaying multi-line, editable text?

A.tk.Listbox()
B.tk.Entry()
C.tk.Text()
D.tk.Label()
AnswerC

tk.Text provides a multi-line editable buffer with insert, delete and index operations, unlike single-line Entry or read-only Label. It directly satisfies the requirement for displaying and editing multi-line content, supporting scrolling, tags and cursor navigation out of the box.

Why this answer

tk.Text is the Tkinter widget designed for multi-line, editable text input, supporting scrolling, indexing, tags, and embedded windows/images. It is the correct choice when users need to enter or edit paragraphs of text. Entry and Label are single-line or read-only, and Listbox is for selecting items from a list.

Exam trap

PCPP1 often tests whether candidates distinguish single-line Entry from multi-line Text, and whether they confuse read-only Label with editable input widgets.

How to eliminate wrong answers

Option A is wrong because tk.Listbox displays a scrollable list of items for selection; it does not support free-form multi-line text editing. Option B is wrong because tk.Entry is a single-line text input widget; it cannot display or edit multiple lines. Option D is wrong because tk.Label is a read-only display widget for static text or images; it is not editable at all.

248
Multi-Selecteasy

Which TWO of the following are valid conventions for naming in Python according to PEP 8?

Select 2 answers
A.Constants: camelCase
B.Classes: PascalCase
C.Modules: PascalCase
D.Functions: camelCase
E.Variables: snake_case
AnswersB, E

PEP 8 prescribes PascalCase (CapWords) for class names, satisfying the stem's requirement for a valid naming convention. Each word is capitalised without underscores, as in `class HttpClient:`. This distinguishes classes from functions and variables, which use snake_case, and constants, which use UPPER_CASE.

Why this answer

Option B is correct because PEP 8 specifies that class names should use the CapWords (PascalCase) convention, e.g., class MyClass. Option E is correct because PEP 8 states that variable names should be lowercase with words separated by underscores (snake_case), e.g., my_variable. The unmarked options are incorrect: constants should be UPPER_CASE_WITH_UNDERSCORES, not camelCase (A); modules should be short, all-lowercase names, preferably with underscores, not PascalCase (C); and functions should be lowercase with underscores (snake_case), not camelCase (D).

Exam trap

PCPP1 often tests PEP 8 naming conventions, and candidates confuse camelCase (common in Java/JavaScript) with Python's snake_case for functions and variables, or mistakenly use PascalCase for modules.

249
MCQhard

You are building a REST client that needs to handle 429 Too Many Requests status codes. Which strategy is most effective when implementing an automatic retry mechanism?

A.Implement an exponential backoff strategy with jitter
B.Switch to a different base URL immediately
C.Ignore 429 errors and continue execution
D.Retry immediately in a loop until successful
AnswerA

Exponential backoff with jitter progressively lengthens delays between retries while randomising them, preventing thundering-herd synchronisation. This directly addresses the 429 constraint by spacing retries so the client stops overwhelming the rate-limited server, unlike fixed-interval retries that keep colliding.

Why this answer

Implementing exponential backoff ensures that you do not overwhelm the server while waiting for the rate limit to reset.

250
Multi-Selectmedium

Which THREE practices improve documentation maintenance?

Select 3 answers
A.Updating documentation as part of the code review process.
B.Writing docs only at the end of the project.
C.Following a consistent docstring format (e.g., Google).
D.Keeping documentation in a separate repository.
E.Using automatic documentation generation tools like Sphinx.
AnswersA, C, E

Reviewing documentation alongside code changes keeps it synchronised with behaviour, since reviewers already inspect the diff. This satisfies the maintenance constraint by making documentation updates a gate in the existing workflow rather than a separate, easily deferred task.

Why this answer

Option A is correct because integrating documentation updates into the code review process makes doc changes a required, verifiable part of every pull request, so docs stay synchronized with code changes instead of drifting out of date. Option C is correct because following a consistent docstring format such as Google style enforces a uniform structure for parameters, returns, and raises sections, which makes documentation easier to read, review, and parse by tooling. Option E is correct because automatic documentation generation tools like Sphinx build docs directly from source docstrings, so regenerating after each change keeps published documentation current with minimal manual effort.

Option B is not correct because writing docs only at the end of a project causes them to lag behind implementation and often results in incomplete or stale content. Option D is not correct because keeping documentation in a separate repository decouples it from the code, making it harder to update in the same commit or review cycle and increasing the risk of version mismatch.

251
MCQeasy

Which attribute of a Button widget controls the text displayed on it?

A.value
B.text
C.caption
D.label
AnswerB

The text attribute of a Button widget stores and displays the caption shown on the button face. Setting it changes the visible label, whereas attributes such as command or state govern behaviour rather than the displayed string.

Why this answer

The 'text' parameter defines the display label of the button.

252
MCQmedium

You are designing a plugin registry that must automatically register every concrete subclass of a base class `Plugin` at the moment the subclass is defined, without requiring any explicit registration call in the subclass body. You want to avoid a metaclass because the project already uses `ABCMeta` for the base class and you do not want to introduce metaclass conflicts. Which approach best satisfies this requirement?

A.Use `__subclasses__()` on `Plugin` inside a periodic background thread and append any newly discovered subclasses to the registry.
B.Override `__set_name__` on `Plugin` so that each subclass reports its name to the registry when the class body finishes executing.
C.Define `__init_subclass__` as a classmethod on `Plugin` that appends the newly created class to a registry list.
D.Define `__new__` on `Plugin` and insert the class into the registry whenever `Plugin` itself is instantiated.
AnswerC

`__init_subclass__` is an implicit classmethod invoked on the parent class immediately after each subclass is created, receiving the new class as its first argument. It runs automatically at class-definition time, so no explicit registration call is needed in the subclass body. Because it is just a normal method, it composes cleanly with `ABCMeta` instead of replacing or conflicting with it.

Why this answer

The implicit `__init_subclass__` classmethod is executed by Python on the parent class right after a subclass is created, so it provides exactly the definition-time hook the registry needs. It is a plain method, so it coexists with `ABCMeta` and other metaclasses without conflict. Hooks tied to instantiation or descriptor binding run at the wrong moment and cannot reliably capture every concrete or abstract subclass.

Exam trap

The trap here is confusing hooks that run at class-definition time with hooks like `__new__` that only run when an instance is constructed.

253
MCQmedium

A developer is writing a Python module and wants to follow PEP 8's recommendations for imports. The module currently has the following imports: `import os`, `import sys`, `import requests`, `from collections import defaultdict`. According to PEP 8, how should these imports be grouped and ordered?

A.Standard library imports first, then third-party imports, each group separated by a blank line.
B.All imports should be sorted alphabetically regardless of origin.
C.Imports should be placed on separate lines, and no blank lines are needed between groups.
D.Third-party imports first, then standard library imports, to highlight external dependencies.
AnswerA

PEP 8 recommends grouping imports in the following order: standard library imports, related third-party imports, and local application/library specific imports. Each group should be separated by a blank line. In this case, `os`, `sys`, and `collections` are standard library, while `requests` is third-party. So the correct grouping is standard library imports first, then third-party, with a blank line between groups.

Why this answer

PEP 8 specifies that imports should be grouped in the order: standard library, third-party, and local application/library specific. Each group should be separated by a blank line. In the given scenario, `os`, `sys`, and `collections` are standard library, while `requests` is third-party.

Therefore, standard library imports should come first, followed by a blank line, then third-party imports.

Exam trap

The trap here is thinking that imports should be sorted purely alphabetically, ignoring the grouping by origin that PEP 8 recommends.

254
MCQeasy

What happens when you add two objects of a class that implements __add__?

A.It does nothing.
B.It concatenates the objects.
C.It raises a TypeError.
D.The __add__ method is called.
AnswerD

Python's binary operator protocol dispatches addition to the left operand's type: evaluating a + b invokes type(a).__add__(a, b). Since the class defines __add__, that method executes, receiving self and the other operand, and its return value becomes the expression's result.

Why this answer

The __add__ method is automatically called by the interpreter when the '+' operator is used.

255
Multi-Selectmedium

Which TWO of the following are required to successfully write a row to a CSV file?

Select 2 answers
A.A list of strings to write.
B.An instance of csv.writer.
C.A call to csv.close().
D.A predefined dialect.
E.A file object opened in write mode.
AnswersB, E

Writing rows requires a csv.writer instance, obtained by passing an open file object to csv.writer(). This object supplies the writerow() and writerows() methods that serialise Python sequences into delimited text, satisfying the stem's requirement for a mechanism that actually performs the CSV write operation.

Why this answer

To write a row to a CSV file with Python's csv module, you must first create an instance of csv.writer (option B), because csv.writer wraps a file-like object and provides the writerow()/writerows() methods that perform the CSV formatting and writing. You also need a file object opened in write mode (option E), such as one returned by open('file.csv', 'w', newline=''), since csv.writer writes to that underlying file object and cannot write to a path or a read-only handle. Option A is not required because the row data can be any iterable (e.g., tuple, generator), not strictly a list of strings, and the values need not all be strings since the writer converts them.

Option C is incorrect because there is no csv.close() function; you close the underlying file object (or use a with block), not the csv module. Option D is incorrect because a predefined dialect is optional — csv.writer defaults to the 'excel' dialect if none is supplied.

256
MCQhard

You are developing a Python script that needs to determine the absolute path of a file located in a directory relative to the script's location. You decide to use the os.path module. Which of the following functions should you use to obtain the absolute path without resolving symbolic links?

A.os.path.normpath()
B.os.path.realpath()
C.os.path.join()
D.os.path.abspath()
AnswerD

os.path.abspath() returns the absolute path of a given path, normalizing it by removing '..' and '.' components, but it does not resolve symbolic links. It simply prepends the current working directory if the path is relative. This is exactly what is needed when you want the absolute path without following symlinks. It is a straightforward and efficient way to get the absolute path.

Why this answer

os.path.abspath() computes an absolute path by combining the current working directory with the given path, normalizing it without resolving symbolic links. This matches the requirement. os.path.realpath() would resolve symlinks, os.path.normpath() only normalizes, and os.path.join() only concatenates components. Thus, abspath is the correct choice.

Exam trap

The trap here is confusing os.path.abspath() with os.path.realpath(), assuming both resolve symlinks, but only realpath does.

257
MCQeasy

When using the 'requests' library to perform a GET request, which parameter should be passed to the 'params' argument to include query string parameters in the URL?

A.A tuple of values
B.A single formatted string
C.A list of strings
D.A dictionary
AnswerD

The params argument accepts a dictionary of key-value pairs, which requests URL-encodes and appends to the query string. Passing a dictionary therefore satisfies the stem's requirement to include query string parameters in the GET request URL.

Why this answer

The requests library's params argument accepts a dictionary (or list of tuples) that it URL-encodes and appends as a query string. Passing a dict like {'q': 'python', 'page': 2} produces ?q=python&page=2 automatically. This is the idiomatic and documented usage for GET query parameters.

Exam trap

PCPP1 often tests whether candidates know that params expects a mapping (dict) or sequence of two-tuples, not a pre-formatted string or bare list, since manual URL building is a common but incorrect habit.

How to eliminate wrong answers

Option A is wrong because a tuple of values alone lacks keys and would not map to query parameter names; requests expects key-value pairs, not bare values. Option B is wrong because a single formatted string would be treated as a raw value or require manual URL construction, defeating the purpose of params and risking encoding errors. Option C is wrong because a list of strings lacks key-value structure; while a list of tuples is valid, a plain list of strings is not the documented form and would not produce correct query parameters.

258
MCQhard

You are using configparser.ConfigParser to read a configuration file. You have a file where option names are case-sensitive. How do you ensure the parser respects this casing?

A.parser = ConfigParser(case_sensitive=True)
B.parser.set_case(True)
C.parser.optionxform = lambda x: x
D.parser.read(file, case='preserve')
AnswerC

Assigning an identity lambda to `optionxform` disables configparser's default lowercasing of option names, which is the mechanism that otherwise destroys case sensitivity. The stem's constraint — case-sensitive option names — is satisfied because keys are stored exactly as written in the file.

Why this answer

By default, ConfigParser converts keys to lowercase. You must override the optionxform method of the parser instance.

259
MCQhard

If you define a class with a metaclass that has a custom __call__ method, when is that __call__ method executed?

A.Every time an instance method is called.
B.When an instance of the class is created.
C.When the metaclass is first imported.
D.When the class itself is defined.
AnswerB

A metaclass's `__call__` intercepts instantiation of the class it builds, running when you call the class to create an instance. It satisfies the stem's constraint by executing at instance-creation time, before `__init__` and `__new__` of the class itself, allowing the metaclass to customise or replace the returned object.

Why this answer

The metaclass's __call__ method is invoked whenever the class created by that metaclass is instantiated (i.e., when you call the class name like MyClass()).

260
MCQhard

You are configuring logging using a dictConfig. You want to send logs to a RotatingFileHandler. Which key must you define in the 'handlers' section?

A.destination
B.type
C.handler_type
D.class
AnswerD

Specifying `class` tells dictConfig which handler type to instantiate, here `logging.handlers.RotatingFileHandler`, satisfying the requirement to route logs through a rotating file handler. Without it, dictConfig cannot resolve the handler factory, so the configuration fails. Other keys such as `filename` or `level` merely configure the instance after creation.

Why this answer

The 'class' key is required to specify the handler type, e.g., 'logging.handlers.RotatingFileHandler'.

261
MCQmedium

You need a color chooser dialog in your application. Which module contains this functionality?

A.tkinter.dialogs
B.tkinter.colorchooser
C.tkinter.colors
D.tkinter.widgets
AnswerB

`tkinter.colorchooser` provides the `askcolor()` function, which opens a native colour picker dialog and returns the chosen RGB values and hexadecimal string. It satisfies the stem's requirement for a colour chooser dialog directly, without extra dependencies, unlike `tkinter.ttk` widgets or third-party libraries.

Why this answer

The 'tkinter.colorchooser' module provides the askcolor() function.

262
MCQmedium

You need to configure the logging module to capture logs from multiple modules while ensuring that logs from third-party libraries (e.g., 'urllib3') are only captured at the WARNING level. How do you set this?

A.logging.getLogger('urllib3').setLevel(logging.WARNING)
B.logging.config.dictConfig({'urllib3': 'WARNING'})
C.logging.basicConfig(level=logging.WARNING)
D.logging.setLevel('urllib3', logging.WARNING)
AnswerA

Setting the level on the 'urllib3' logger object directly raises its effective threshold to WARNING, so DEBUG and INFO records from that library are discarded while your own modules keep their configured levels. This satisfies the constraint of suppressing third-party noise without altering root logger behaviour.

Why this answer

You can configure individual loggers using getLogger() and setting their specific level attribute.

263
MCQhard

You are designing a Python application that consumes a REST API which returns JSON data. The API responses can be large, and you need to process the JSON incrementally to avoid loading the entire response into memory. The server supports chunked transfer encoding. Which of the following techniques should you use with the 'requests' library to stream the response and parse it incrementally?

A.Set stream=True in the request and use response.iter_content() to read chunks, then parse each chunk with a streaming JSON parser like ijson.
B.Use response.json() directly; it automatically streams and parses the JSON without loading everything into memory.
C.Use requests.get() with a large timeout and rely on the operating system's memory management to handle the response.
D.Set stream=True and then call response.json() to parse the streamed data.
AnswerA

Setting 'stream=True' prevents 'requests' from immediately downloading the entire response body. You can then use 'response.iter_content()' to iterate over the response data in chunks. To parse JSON incrementally, you need a streaming parser like 'ijson' that can process partial JSON data. This approach minimizes memory usage, which is critical for large responses.

Why this answer

To process large JSON responses incrementally with 'requests', you must enable streaming with 'stream=True' and then read the response in chunks using 'response.iter_content()'. Since JSON is not inherently line-delimited, you need a streaming parser like 'ijson' to parse the chunks as they arrive. This avoids loading the entire response into memory, making it suitable for large datasets.

Exam trap

The trap here is thinking that 'response.json()' works with streaming, or that setting 'stream=True' alone is enough without a streaming JSON parser.

264
Multi-Selecteasy

Which TWO of the following are valid ways to terminate a Tkinter script gracefully?

Select 2 answers
A.os.kill()
B.root.quit()
C.exit()
D.root.close()
E.root.destroy()
AnswersB, E

Calling `root.quit()` stops Tkinter's main loop, letting the script continue past `mainloop()` and exit cleanly. Unlike `root.destroy()`, which tears down the window and all widgets, `quit()` merely halts event processing, satisfying the requirement for graceful termination without destroying the application's widget hierarchy.

Why this answer

Option B, root.quit(), is correct because it tells the Tkinter mainloop to stop processing events and return control to the code after mainloop(), which is the standard graceful way to end the event loop while allowing cleanup code to run. Option E, root.destroy(), is also correct because it destroys the root window and all its child widgets, causing the mainloop to exit and the application to terminate cleanly. Option A, os.kill(), is not appropriate because it sends a low-level signal to a process (e.g., SIGTERM/SIGKILL) rather than performing a Tkinter-aware shutdown, so it bypasses widget cleanup.

Option C, exit(), is not a Tkinter method and is intended for interactive interpreters; calling it in a GUI script raises SystemExit abruptly rather than gracefully stopping the Tk mainloop. Option D, root.close(), is invalid because Tkinter's Tk root object has no close() method; the correct window-closing method is destroy().

265
MCQeasy

Which method is used to customize the behavior of the 'in' operator?

A.__contains__
B.__has__
C.__find__
D.__in__
AnswerA

Defining `__contains__` on a class lets Python delegate membership tests to it, so `x in instance` invokes your logic instead of falling back to iteration via `__iter__` or `__getitem__`. This directly customises the `in` operator's behaviour, satisfying the stem's requirement precisely.

Why this answer

The __contains__ method is called when using the 'in' or 'not in' operators.

266
Multi-Selecthard

You are implementing a REST API client in Python using the 'requests' library. The API requires authentication using OAuth 2.0. You need to obtain an access token and then use it to authenticate subsequent requests. Which TWO of the following statements about handling OAuth 2.0 with 'requests' are correct? (Choose two.)

Select 2 answers
A.OAuth 2.0 access tokens are typically sent as query parameters in the URL.
B.You can use the 'requests-oauthlib' library to handle the OAuth 2.0 flow, including token refresh.
C.The 'requests' library automatically refreshes expired OAuth 2.0 tokens when using the 'auth' parameter.
D.The 'requests' library includes built-in support for OAuth 2.0 token management.
E.You can manually add the access token to requests by setting the 'Authorization' header to 'Bearer <token>'.
AnswersB, E

'requests-oauthlib' is a popular extension that integrates OAuth 2.0 with 'requests'. It provides 'OAuth2Session', which manages token acquisition, storage, and automatic refreshing. This is the recommended approach for complex OAuth flows, as it handles redirects, state parameters, and token expiration, reducing the risk of manual errors.

Why this answer

Handling OAuth 2.0 with 'requests' typically involves either using a specialized library like 'requests-oauthlib' for full flow management, or manually adding the Bearer token to the Authorization header if you already have a valid token. The core 'requests' library does not provide built-in OAuth 2.0 support, and sending tokens as query parameters is insecure and not recommended.

Exam trap

The trap here is assuming that 'requests' has built-in OAuth 2.0 support or that the 'auth' parameter handles token refresh, when in fact it is for Basic Authentication.

267
Multi-Selecthard

Which TWO of the following are secure coding practices in Python?

Select 2 answers
A.Use 'subprocess' with 'shell=True'.
B.Always use 'eval()' for dynamic execution.
C.Avoid using 'pickle' for untrusted data.
D.Validate and sanitize all user input.
E.Use hardcoded credentials for database connections.
AnswersC, D

Unpickling executes arbitrary code via the __reduce__ mechanism, so a crafted payload from an untrusted source achieves remote code execution. Avoiding pickle for untrusted data removes that deserialisation attack surface, matching the secure coding requirement.

Why this answer

Option C is correct because Python's 'pickle' module is inherently unsafe for untrusted data: unpickling executes arbitrary code via the __reduce__ method, so deserializing attacker-controlled bytes can lead to remote code execution; safe alternatives include 'json' or other non-executable formats. Option D is correct because validating and sanitizing all user input (e.g., using allowlists, type checks, and parameterized queries) prevents injection flaws such as SQL injection, command injection, and XSS, forming a core secure coding practice. Option A is wrong because 'subprocess' with 'shell=True' passes the command through the shell, enabling shell metacharacter injection; the safe practice is 'shell=False' with an argument list.

Option B is wrong because 'eval()' executes arbitrary Python expressions and is a classic code-injection vector; dynamic execution should use safer mechanisms like 'ast.literal_eval' for literals. Option E is wrong because hardcoded credentials in source code expose secrets and violate secure secret-management practices such as using environment variables or a secrets manager.

268
MCQmedium

You are consuming a REST API that returns data in JSON format. After calling response.json(), you notice the data contains nested dictionaries. What is the most Pythonic way to handle a missing key in the response dictionary safely?

A.Wrap the access in a try-except KeyError block
B.Check 'if 'key' in response.json():' before access
C.Use response.json()['key'] and assume the API schema is always correct
D.Use response.json().get('key', default_value)
AnswerD

dict.get returns the supplied default when the key is absent, avoiding a KeyError without try/except. This handles missing keys in the nested JSON-derived dictionary safely and concisely, satisfying the stem's requirement for the most Pythonic approach.

Why this answer

The dict.get() method provides a way to access a key with a default value if the key does not exist, preventing a KeyError.

269
MCQeasy

What is the primary function of the 'bg' parameter in a widget configuration?

A.Sets the button group.
B.Sets the border group.
C.Sets the background color.
D.Sets the base grid.
AnswerC

The `bg` parameter directly assigns a widget's background colour, satisfying the stem's requirement for its primary function. Tkinter applies this value to the widget's background pixel area, distinct from `fg`, which controls foreground text or content colour. No other parameter governs background rendering, confirming `bg` as the correct attribute.

Why this answer

In widget configuration (as used in Python GUI frameworks such as Tkinter and similar toolkits), the 'bg' parameter is the standard abbreviation for 'background', and it sets the background colour of the widget. It accepts colour names (e.g., 'red', 'blue') or hexadecimal colour codes (e.g., '#FF0000').

Exam trap

The trap here is that 'bg' is a short abbreviation, and candidates may guess at its meaning — the exam expects you to know that 'bg' universally stands for 'background' in widget configuration contexts, not 'button group', 'border group', or 'base grid'.

How to eliminate wrong answers

Option A is wrong because 'button group' would typically be configured via a different parameter (e.g., 'group' or a container widget), not 'bg'. Option B is wrong because 'border group' is not a standard widget configuration parameter, and border settings are usually controlled by 'bd' (border width) or 'relief'. Option D is wrong because 'base grid' is not a widget configuration parameter — grid geometry is managed by the 'grid()' method, not a 'bg' option.

270
MCQmedium

You are building a configuration manager that reads an INI file. A section contains the key-value pair `timeout = 30`. You need to retrieve the value as an integer, but if the key is missing, you want to get 60 without raising an exception. Which code snippet achieves this using the `configparser` module?

A.int(config.get('section', 'timeout', fallback=60))
B.config.getint('section', 'timeout', fallback=60)
C.config['section'].getint('timeout', 60)
D.config.getint('section', 'timeout', default=60)
AnswerB

The `getint` method of a `ConfigParser` instance converts the value to an integer and accepts a `fallback` keyword argument that is returned if the key is missing. This directly satisfies the requirement to get an integer or a default without raising an exception. The other options either do not convert to integer or do not handle missing keys gracefully.

Why this answer

The `getint` method of the `ConfigParser` class retrieves a value and converts it to an integer. It accepts a `fallback` argument that is returned if the key is not found, preventing a `NoOptionError`. This is the standard way to handle optional integer settings in INI files.

Exam trap

The trap here is confusing the `fallback` parameter of `configparser` methods with the `default` parameter used in other configuration libraries or the `default` argument of `dict.get`.

271
MCQeasy

Which magic method should you implement to make your objects support the 'with' statement context manager?

A.__context__
B.__enter__ and __exit__
C.__open__ and __close__
D.__init__ and __del__
AnswerB

The with statement calls __enter__ on entry and __exit__ on exit, the latter receiving exception details for cleanup or suppression. Implementing both satisfies the stem's context manager requirement, since neither method alone enables the protocol.

Why this answer

The __enter__ and __exit__ methods are required to implement the context manager protocol.

272
MCQeasy

Which function is used to check if an object is an instance of a class?

A.hasattr()
B.issubclass()
C.type()
D.isinstance()
AnswerD

`isinstance()` accepts an object and a class (or tuple of classes) and returns a Boolean, resolving the object's type through its class hierarchy, including inherited and virtual subclasses. This directly satisfies the stem's requirement to check whether an object is an instance of a class, unlike identity or equality comparisons.

Why this answer

isinstance(obj, Class) is the standard way to check inheritance.

273
MCQmedium

You want to bind a function 'on_click' to a left mouse button click on a Button widget. Which event sequence string is correct?

A.<Button-1>
B.<Mouse-1>
C.<Left-Click>
D.<Click-1>
AnswerA

Tkinter encodes mouse events as <MODIFIER-BUTTON-NUM>, where Button-1 denotes the left mouse button. Binding <Button-1> to the Button widget therefore fires on_click precisely on a left click, satisfying the stem's requirement without capturing middle or right button presses.

Why this answer

The event sequence '<Button-1>' corresponds to the primary (left) mouse button.

274
MCQmedium

In the context of the Factory pattern in Python, what is a typical benefit of using a registry-based approach instead of a large if-else block?

A.It guarantees thread safety without locks.
B.It prevents the instantiation of abstract classes.
C.It enables easy extension by adding new products without changing the factory.
D.It significantly reduces memory usage.
AnswerC

A registry maps product identifiers to creator callables, so new products register themselves at import time. This satisfies the open/closed constraint: the factory function stays untouched, eliminating the if-else chain that would otherwise require editing whenever a product type is added.

Why this answer

A registry-based factory stores a mapping (typically a dict) from product identifiers to their concrete classes or creator callables, so the factory simply looks up and instantiates the requested product. Adding a new product means registering it in the mapping — no modification to the factory's control flow is required, satisfying the Open/Closed Principle. This decouples the factory from concrete product classes and makes extension a configuration concern rather than a code change.

Exam trap

PCPP1 often tests whether candidates confuse the extensibility benefit of the registry pattern with unrelated concerns like thread safety or memory optimization, luring them toward plausible-sounding but technically unrelated options.

How to eliminate wrong answers

Option A is wrong because registry lookups are not inherently thread-safe — concurrent registration or mutation of the registry dict still requires locks or a thread-safe structure like a lock-protected dict or concurrent mapping. Option B is wrong because preventing abstract class instantiation is the job of abc.ABCMeta/abstractmethod or raising NotImplementedError, not of the registry pattern itself. Option D is wrong because a registry adds a dict of references and does not meaningfully reduce memory usage; memory footprint is dominated by the product instances, not the lookup mechanism.

275
MCQmedium

How do you properly handle a non-200 status code when using 'requests' if you want to avoid manual status code checking?

A.Use response.raise_for_status()
B.Use a decorator on the request function
C.Check response.error
D.The library raises an exception by default
AnswerA

`response.raise_for_status()` inspects the status code internally and raises an `HTTPError` exception for any 4xx or 5xx response, so you never write an explicit `if response.status_code != 200` check. Wrapping the call in `try`/`except requests.exceptions.HTTPError` satisfies the stem's requirement to avoid manual status code checking.

Why this answer

Calling response.raise_for_status() will raise an HTTPError exception if the status code indicates an error (4xx or 5xx).

276
MCQmedium

You are processing a CSV file using csv.DictReader. If your input file lacks a header row, how do you provide the field names?

A.csv.DictReader(f, headers=['a', 'b'])
B.csv.DictReader(f).map(['a', 'b'])
C.csv.DictReader(f, fieldnames=['a', 'b'])
D.csv.DictReader(f, columns=['a', 'b'])
AnswerC

DictReader normally consumes the first row as field names. Passing fieldnames explicitly overrides that behaviour, so each subsequent row is mapped to the supplied keys in order, satisfying the constraint of a headerless file without manual index lookups.

Why this answer

You pass the 'fieldnames' argument to the constructor to define the headers explicitly.

277
Multi-Selectmedium

A Python developer is writing a function that reads a configuration file and returns a dictionary. They want to follow PEP 8 and best practices for function design and documentation. Which two of the following should they do? (Choose two.)

Select 2 answers
A.Place the function at the top of the file, before any imports, to make it easily accessible.
B.Include a docstring that describes the function's purpose, parameters, and return value.
C.Raise a generic `Exception` if the file cannot be read, to keep error handling simple.
D.Use a descriptive function name in lowercase with underscores, such as `read_config_file`.
E.Use a single-letter parameter name like `f` for the file path to keep the signature short.
AnswersB, D

PEP 257 recommends that all public functions include a docstring. A good docstring explains what the function does, its parameters, and its return value. This practice is essential for documentation generation tools and for other developers to understand the function's behavior without reading the implementation. It aligns with best practices for writing clear, maintainable code and is expected in professional Python projects.

Why this answer

Following PEP 8 and best practices, function names should be descriptive and use lowercase with underscores, and public functions should have docstrings that explain their purpose, parameters, and return values. These practices enhance code readability and maintainability. The other options either use unclear parameter names, raise overly broad exceptions, or misplace the function relative to imports, all of which violate established conventions.

Exam trap

The trap here is focusing on brevity (short parameter names, simple error handling) at the expense of clarity and specificity, which PEP 8 explicitly discourages.

278
MCQmedium

A team is reviewing a module where a helper function `_normalize_path` is prefixed with a single underscore. A new developer asks which statement best describes the intent of that naming choice according to common Python conventions.

A.The single underscore marks the function as deprecated and scheduled for removal in a future release.
B.The single underscore signals that the function is intended for internal use and is not part of the module's public API.
C.The single underscore makes the function inaccessible from outside the module at runtime.
D.The single underscore indicates that the function is a special method recognized by the Python interpreter.
AnswerB

A leading single underscore is a widely recognized convention indicating that a name is meant for internal use. It does not enforce privacy at runtime, but it tells other developers that the function is an implementation detail and may change without notice. This matches the intent of `_normalize_path` as a helper rather than a public entry point.

Why this answer

A leading single underscore is a convention that marks a name as internal, signaling that it is not part of the public API and may change without notice. It provides no runtime enforcement, so callers can still use it, but doing so is discouraged. This convention helps communicate intent in `_normalize_path` without altering behavior.

Exam trap

The trap here is believing that a single leading underscore enforces privacy at runtime rather than serving purely as a naming convention.

279
MCQmedium

You are writing a Python script that must download a large file from a REST API endpoint. The file is several gigabytes, and you want to avoid loading it entirely into memory. Which approach using the requests library is most memory-efficient?

A.Use requests.get(url).content to get the raw bytes and write them to a file in one operation.
B.Use requests.get(url, timeout=300) and then use shutil.copyfileobj(response.raw, file) to copy the raw stream to a file.
C.Use requests.get(url, stream=True) and call response.raw.read() to read the entire raw stream at once.
D.Use requests.get(url, stream=True) and iterate over response.iter_content(chunk_size=8192), writing each chunk to a file.
AnswerD

Setting stream=True defers downloading the response body until you access it. Then iter_content() yields chunks of the specified size, allowing you to write them to disk incrementally. This keeps memory usage low and constant, regardless of file size. It is the recommended approach for downloading large files with requests.

Why this answer

Using stream=True prevents the response body from being downloaded immediately. Iterating over iter_content() with a chunk size writes data to disk incrementally, keeping memory usage low. Other methods either load the entire response into memory or fail to stream properly.

This is the standard pattern for large file downloads with requests.

Exam trap

The trap here is assuming that stream=True alone is sufficient, without also using iter_content() to read in chunks; reading the raw stream all at once still consumes memory.

280
MCQmedium

You are debugging a legacy application and need to ensure that resources like file handles are always closed. Which construct is preferred?

A.Wrap the file operation in a try-except block.
B.Manually call file.close() in a finally block.
C.Use a context manager with the 'with' statement.
D.Rely on the garbage collector to close the handle.
AnswerC

A context manager using 'with' guarantees __exit__ runs on block exit, including on exceptions, so file handles close deterministically. This satisfies the legacy-code constraint of always releasing resources, unlike relying on garbage collection or manual close calls that can be skipped.

Why this answer

The 'with' statement invokes a context manager, which guarantees that the __exit__ method runs and closes the file handle even if an exception occurs inside the block. This is the idiomatic, preferred Python construct for deterministic resource cleanup. It is cleaner and safer than manual try/finally code.

Exam trap

PCPP1 often tests the misconception that try/finally or garbage collection is equivalent to 'with'; only the context manager guarantees deterministic, exception-safe cleanup.

How to eliminate wrong answers

Option A is wrong because a try-except block alone does not guarantee the file is closed — it only handles exceptions, and the handle may leak if no close is called. Option B is wrong because while a finally block does close the file, it is more verbose and error-prone than the 'with' statement, and it is not the preferred construct. Option D is wrong because relying on the garbage collector is non-deterministic and may delay or never close the handle, especially in CPython where reference counting usually closes it but other implementations may not.

281
MCQmedium

How do you set a specific font for a widget?

A.widget.set_font('Arial', 12)
B.widget.style('Arial', 12)
C.widget.font = 'Arial 12'
D.widget.config(font=('Arial', 12))
AnswerD

Tkinter's config method accepts a font option, and a tuple of family and size sets that widget's typeface directly. Passing ('Arial', 12) assigns Arial at 12 points to the widget, satisfying the requirement to set a specific font.

Why this answer

The 'font' parameter accepts a tuple or string defining font family, size, and style.

282
MCQmedium

You are using sqlite3 and need to enforce foreign key constraints. How do you enable them?

A.It is enabled by default.
B.connection.execute('PRAGMA foreign_keys = ON')
C.connection.execute('SET FOREIGN_KEYS ON')
D.connection.enable_foreign_keys()
AnswerB

SQLite disables foreign key enforcement by default per connection, so the PRAGMA must be issued on the live connection object. Executing 'PRAGMA foreign_keys = ON' via connection.execute activates constraint checking for that session, satisfying the requirement to enforce referential integrity.

Why this answer

You must execute the command 'PRAGMA foreign_keys = ON;' on the connection.

283
MCQhard

Why might you use the __init_subclass__ hook instead of a metaclass?

A.Metaclasses are deprecated.
B.Metaclasses cannot be used for registration.
C.It is faster at runtime.
D.It is easier to implement and avoids metaclass conflicts.
AnswerD

`__init_subclass__` runs automatically on subclass creation without a separate metaclass, so it satisfies the stem's need to hook subclassing while avoiding metaclass conflicts. It is a plain classmethod on the parent, simpler to implement than a metaclass, and coexists with any existing metaclass.

Why this answer

__init_subclass__ provides a simpler way to perform logic when a subclass is created, without the complexity and inheritance issues associated with custom metaclasses.

284
MCQhard

You are building a custom HTTP client and need to handle persistent connections (keep-alive). What is the primary role of the 'Connection' header?

A.To signal that the server is alive
B.To request the reuse of the TCP connection
C.To encrypt the connection
D.To set the timeout for the connection
AnswerB

The Connection header signals whether the TCP connection should stay open after the current exchange, with keep-alive requesting reuse rather than closure. This satisfies the persistent-connection requirement, letting subsequent requests travel over the same socket instead of triggering a new handshake.

Why this answer

The 'Connection: keep-alive' header tells the server that the client wants to reuse the same TCP connection for multiple requests.

285
Multi-Selecthard

Which TWO of the following are true about the sqlite3.Cursor object?

Select 2 answers
A.It can be used as an iterator to fetch rows.
B.It is used to execute SQL statements.
C.It automatically creates a transaction for every SELECT.
D.It is limited to one active query.
E.It keeps track of the connection state.
AnswersA, B

A Cursor implements the iterator protocol, so iterating it yields successive rows from the last executed SELECT without repeated fetchone calls. This is distinct from the Connection, which is not iterated for rows in this manner.

Why this answer

Option A is correct because a sqlite3.Cursor implements the iterator protocol, so you can loop over it directly (e.g., 'for row in cursor:') to fetch rows one at a time from the result set. Option B is correct because the Cursor object provides the execute(), executemany(), and executescript() methods that are used to run SQL statements against the database. Option C is incorrect because transaction handling is a property of the Connection object, not the Cursor; SELECT statements do not automatically open a transaction in the way described.

Option D is incorrect because a single Cursor can be reused for multiple sequential queries, and multiple cursors can exist on one connection. Option E is incorrect because connection state (such as open/closed status and transaction control) is tracked by the sqlite3.Connection object, not the Cursor.

286
Multi-Selecteasy

Which THREE of the following are valid ways to pass data to a REST API using 'requests'?

Select 3 answers
A.json
B.socket
C.url
D.params
E.data
AnswersA, D, E

The json parameter accepts a Python object, serialises it to JSON and sets the Content-Type header to application/json automatically. This satisfies the stem's requirement for passing data to a REST API, differing from data, which sends raw form-encoded bytes without JSON serialisation.

Why this answer

Option A, json, is correct because passing a Python object to the json= parameter serializes it to JSON and sends it in the request body with Content-Type: application/json, which is the standard way to submit JSON payloads to a REST API. Option D, params, is correct because params= appends a dictionary of key/value pairs as a URL query string (e.g., ?key=value), which REST APIs commonly use for filtering, pagination, or search arguments. Option E, data, is correct because data= sends a dictionary or bytes as the request body, typically form-encoded (application/x-www-form-urlencoded) for POST/PUT/PATCH requests to REST endpoints.

Option B, socket, is not a requests parameter at all — it refers to low-level network programming, not the requests library's API. Option C, url, is not a data-passing mechanism; the url argument specifies the endpoint address, not the payload or query data itself.

287
MCQmedium

Your team uses a REST API that requires a Bearer token in the Authorization header for every request. You want to configure a `requests.Session` so that all requests made through it automatically include this header, and you also want to reuse the underlying TCP connection across calls. Which approach is correct?

A.Set requests.default_headers['Authorization'] = 'Bearer ' + token and call requests.get(url).
B.Call requests.get(url, headers={'Authorization': 'Bearer ' + token}) for every request.
C.Create a Session, set session.headers.update({'Authorization': 'Bearer ' + token}), and use session.get() for subsequent calls.
D.Create a Session and pass auth=('Bearer', token) to session.get() on each call.
AnswerC

Session objects persist headers across requests and reuse the underlying connection pool, which enables keep-alive and reduces latency. Updating session.headers once applies the Authorization header to every request made through that session, exactly matching the requirement.

Why this answer

A requests.Session maintains a connection pool and a persistent set of headers. Setting the Authorization header once on the session applies it to all requests made through that session, and the underlying urllib3 connection pool reuses TCP connections for the same host. This satisfies both the authentication and connection reuse requirements.

Exam trap

The trap here is using the auth parameter for a Bearer token, which produces Basic authentication instead of the required Authorization header format.

288
MCQmedium

You are developing a Tkinter application that includes a Canvas widget for drawing a dynamic bar chart. The chart data updates every second, and you must redraw the bars. To avoid visual flicker and improve performance, you decide to reuse existing canvas items instead of deleting and recreating them. Which Canvas method should you use to change the height of an existing rectangle item identified by its item ID?

A.canvas.coords(item_id, x1, y1, x2, y2)
B.canvas.move(item_id, 0, delta_y)
C.canvas.scale(item_id, x_origin, y_origin, x_scale, y_scale)
D.canvas.itemconfig(item_id, height=new_height)
AnswerA

The coords() method changes the coordinates of an existing canvas item, such as a rectangle defined by two corners. It updates the item in place without deleting or recreating it, which is efficient and avoids flicker. For a rectangle, you provide the new x1, y1, x2, y2 values. This is the correct approach for dynamic updates.

Why this answer

To dynamically update the size of an existing canvas item, you should modify its coordinates. The coords() method allows you to set new coordinates for an item, effectively resizing or repositioning it without deleting and recreating. This is efficient and avoids flicker.

Other methods like itemconfig() are for changing options like fill, move() only translates, and scale() applies proportional scaling, which is not ideal for precise height adjustments.

Exam trap

The trap here is assuming that itemconfig() can change geometric properties like height for all canvas items, but rectangles are defined by coordinates, not a height attribute.

289
MCQeasy

A Python developer is reviewing code and notices that a function has a default argument value set to an empty list: `def append_to(element, target=[]):`. According to best practices, what is the recommended way to handle mutable default arguments?

A.Keep the empty list as the default; Python handles it safely.
B.Use a tuple instead of a list as the default value.
C.Use `None` as the default and create a new list inside the function if needed.
D.Define the default argument inside the function body instead.
AnswerC

Using None as the default avoids the mutable default argument pitfall. Inside the function, you can check if the argument is None and assign a new list, ensuring each call gets a fresh list. This prevents unexpected shared state across calls.

Why this answer

Mutable default arguments are evaluated once at function definition, leading to shared state. The recommended practice is to use None as the default and create a new mutable object inside the function when needed. This ensures each call gets a fresh object unless one is explicitly passed.

Exam trap

The trap here is thinking that Python creates a new default list for each call; in reality, the default is evaluated once and shared across all calls that omit the argument.

290
MCQhard

You have a Tkinter Entry widget and want to retrieve the text currently entered by the user. Which method do you call on the Entry instance?

A.entry.get()
B.entry.content()
C.entry.text()
D.entry.value()
AnswerA

Entry.get() reads the widget's current contents as a string, satisfying the requirement to retrieve user-entered text. It accepts optional index arguments, but with none it returns the entire field, which is the standard Tkinter approach.

Why this answer

The get() method is used to retrieve the current contents of Entry and Text widgets.

Page 3

Page 4 of 4

All pages