Courseiva

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

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

Page 1 of 4

Page 2
1
Multi-Selecthard

Which THREE of the following are true regarding the use of 'threading' and 'requests' in Python?

Select 3 answers
A.Threads share the same memory space
B.Requests is inherently CPU-bound
C.Using a Session object in every thread is a best practice for persistence
D.Threads bypass the GIL entirely
E.Threading is suitable for I/O-bound tasks like API calls
AnswersA, C, E

Threads within one process share the same heap and global interpreter state, so concurrent requests code can read and mutate common objects directly. This shared memory is precisely why synchronisation primitives such as locks are needed to avoid race conditions.

Why this answer

Option A is correct because threads within a single Python process share the same memory space, which allows them to access shared objects and data directly (though this requires synchronization primitives like locks to avoid race conditions). Option C is correct because creating a requests.Session object per thread is a best practice: a Session provides connection pooling and cookie persistence, and since Session objects are not thread-safe, each thread should have its own instance to avoid cross-thread interference. Option E is correct because threading is well suited for I/O-bound tasks such as API calls with the requests library, since threads release the GIL during blocking I/O operations, allowing other threads to run concurrently.

Option B is incorrect because requests is inherently I/O-bound (network operations), not CPU-bound. Option D is incorrect because threads do not bypass the GIL entirely; the GIL still serializes bytecode execution, and threads only release it during I/O or explicit C-level calls.

2
MCQhard

You are using the logging module in a long-running service. You need to ensure that a specific logger named 'app.db' writes DEBUG and higher messages to a file, but its parent logger 'app' must not propagate these DEBUG messages to the root logger. Which configuration achieves this?

A.Set the 'app.db' logger level to DEBUG, add a FileHandler, and set the root logger level to INFO.
B.Set the 'app.db' logger level to DEBUG, add a FileHandler, and set 'app.db'.propagate = False.
C.Set the 'app' logger level to DEBUG, add a FileHandler to 'app.db', and leave propagate at its default.
D.Set the 'app.db' logger level to DEBUG, add a FileHandler, and add a NullHandler to the 'app' logger.
AnswerB

Setting the logger level to DEBUG allows DEBUG and higher messages to be processed. Adding a FileHandler directs them to a file. Setting propagate to False prevents the logger from passing records to its parent 'app' and ultimately the root logger, so DEBUG messages do not reach other handlers. This exactly meets the requirement without affecting other loggers.

Why this answer

To keep DEBUG messages from 'app.db' confined to its own FileHandler, the logger must process DEBUG records and must not propagate them to ancestors. Setting the logger level to DEBUG enables processing, adding a FileHandler writes to the file, and setting propagate to False stops upward propagation. Other options either allow propagation or attempt to control it via unrelated levels or handlers, which does not achieve the isolation.

Exam trap

The trap here is thinking that setting the root logger level or adding a NullHandler to a parent will suppress propagated records, when propagation bypasses level checks and NullHandler only discards records after they have already been passed upward.

3
Multi-Selectmedium

You are consuming a paginated REST API that returns a JSON object with a 'data' list and a 'next' field holding the URL of the following page, or null on the last page. You want a loop that retrieves every record exactly once. Which TWO statements about implementing this loop correctly are true? (Choose two.)

Select 2 answers
A.You should call response.json() once and reuse the parsed object for subsequent pages to save CPU.
B.You must stop the loop when the 'next' field is null, since that signals there are no further pages.
C.You should set verify=False on each request so pagination is not slowed by certificate checks.
D.You should follow the 'next' URL from the response body rather than constructing page numbers yourself, because the API may use opaque cursors.
E.You should assume the 'next' value is always an absolute URL and pass it directly to requests.get without inspection.
AnswersB, D

The contract described in the scenario uses null to mark the final page, so testing for null is the reliable termination condition. Continuing past it would issue a request with no valid target, and stopping earlier would silently drop records, so this check is essential for correctness.

Why this answer

Following the server-provided next link respects opaque pagination tokens, and terminating when that field is null matches the documented contract. Reusing a single parsed body, disabling TLS verification, or assuming next is always absolute all lead to incorrect or fragile behavior, so those statements are not true.

Exam trap

The trap here is treating the next link as a predictable page number and assuming it is always absolute, when it may be a relative path or an opaque cursor.

4
MCQhard

A library defines a base class `Plugin` with `__init_subclass__(cls, **kwargs)` that automatically registers every subclass in a global registry using `cls.__name__`. A developer writes `class MyPlugin(Plugin, priority=5): pass` but the registration fails with a TypeError about unexpected keyword arguments. What is the most likely cause?

A.The base `Plugin.__init_subclass__` signature does not accept or forward `**kwargs`, so `priority=5` reaches `object.__init_subclass__`, which rejects it.
B.`__init_subclass__` must be declared as a classmethod explicitly; otherwise keyword arguments are not forwarded.
C.The registry is full because `__init_subclass__` runs before the class body executes, so `cls.__name__` is not yet available.
D.Keyword arguments passed in a class definition header are only supported on metaclasses, not on `__init_subclass__`.
AnswerA

If `Plugin.__init_subclass__` is defined as `def __init_subclass__(cls):` without `**kwargs`, then the `priority=5` keyword is not consumed. Python then calls `super().__init_subclass__(**kwargs)` implicitly, ultimately reaching `object.__init_subclass__`, which raises TypeError for unexpected arguments. Adding `**kwargs` to the signature and forwarding it resolves the error.

Why this answer

Keyword arguments in a class header are forwarded to the parent's `__init_subclass__`. If that method does not declare `**kwargs` and forward them, the extra keyword reaches `object.__init_subclass__`, which rejects it with TypeError. Adding `**kwargs` to the signature and passing them to `super().__init_subclass__(**kwargs)` fixes the registration.

Exam trap

The trap here is assuming that `__init_subclass__` automatically absorbs arbitrary keyword arguments without the developer declaring and forwarding them.

5
Multi-Selecthard

Which THREE features are associated with robust logging in production applications?

Select 3 answers
A.Log rotation to prevent disk space exhaustion.
B.Logging to 'stdout' exclusively.
C.Configuring log formatters for structured output.
D.Using different logging levels for different environments.
E.Including personal user data in logs.
AnswersA, C, D

Log rotation caps file growth by archiving or deleting older entries once a size or time threshold is reached, directly preventing the disk space exhaustion named in the stem. Without it, unbounded log files eventually fill the volume, halting the application — a failure mode robust production logging must actively guard against.

Why this answer

Option A is correct because log rotation (e.g., via logrotate or size/time-based rolling appenders) caps log file growth and prevents disk space exhaustion, which is a core production reliability concern. Option C is correct because structured output (e.g., JSON formatters) makes logs machine-parseable, enabling reliable aggregation, searching, and alerting in tools like the ELK stack or Splunk. Option D is correct because using different logging levels per environment (e.g., DEBUG in development, WARN or ERROR in production) controls verbosity, reduces noise and cost, and keeps production logs actionable.

Option B is not inherently a robust-logging feature: writing only to stdout can be valid in containerized setups, but 'exclusively' excludes durable file or remote sinks and is not a defining best practice. Option E is incorrect because including personal user data in logs risks privacy violations (e.g., GDPR) and security exposure, so it should be avoided or masked.

6
MCQeasy

Which of the following headers is commonly used in REST APIs to indicate the format of the request body?

A.Authorization
B.Accept
C.Content-Type
D.User-Agent
AnswerC

Content-Type declares the media type of the request payload, letting the server select the correct parser. It satisfies the stem's requirement to indicate the request body's format, unlike Accept, which instead negotiates the response representation the client wants returned.

Why this answer

The 'Content-Type' header tells the server what type of media is being sent in the request body.

7
MCQeasy

In a team environment, which PEP 8 guideline should be applied to maintain consistent indentation when mixing spaces and tabs?

A.Use spaces exclusively for indentation.
B.Use tabs exclusively, as they are more efficient for file size.
C.Always use a combination of tabs and spaces to allow personal editor configuration.
D.Default to the indentation used by the first author of the module.
AnswerA

PEP 8 mandates spaces exclusively, never mixing tabs and spaces, because tab width varies between editors and tools. Using spaces alone guarantees identical rendering across the team's environments, satisfying the consistency constraint in the stem.

Why this answer

PEP 8 explicitly recommends using spaces exclusively for indentation, with four spaces per indentation level. This avoids the ambiguity and inconsistency that arises when tabs and spaces are mixed, which can lead to Python interpreting indentation differently across editors and causing IndentationError or TabError. Using spaces ensures that code looks the same regardless of editor tab width settings.

Exam trap

PCPP1 often tests the specific PEP 8 rule that spaces are preferred over tabs, and candidates may incorrectly think tabs are acceptable if used consistently, but PEP 8 is clear that spaces are the standard.

How to eliminate wrong answers

Option B is wrong because while tabs are more space-efficient in file size, PEP 8 prioritizes readability and consistency over file size, and tabs can be rendered differently across environments. Option C is wrong because mixing tabs and spaces is explicitly discouraged by PEP 8 and can cause Python 3 to raise a TabError. Option D is wrong because defaulting to the first author's indentation style does not guarantee consistency across the team and violates PEP 8's recommendation for spaces.

8
MCQeasy

A developer is writing a Python script that contains a class named `DataProcessor`. According to PEP 8, which naming convention should be used for the class's methods and attributes?

A.Methods and attributes should use `lowercase_with_underscores`.
B.Methods and attributes should use `CapWords` to be consistent with the class name.
C.Methods and attributes should use `camelCase` to match the class name style.
D.Methods should use `lowercase_with_underscores`, but attributes should use `UPPERCASE`.
AnswerA

PEP 8 specifies that method names and instance variables should be lowercase, with words separated by underscores to improve readability. This convention, known as snake_case, is widely used in Python code and is consistent with the naming of functions and variables. For a class like `DataProcessor`, methods such as `process_data` and attributes like `raw_data` would follow this guideline, ensuring clarity and adherence to community standards.

Why this answer

PEP 8 recommends that method names and instance variables use lowercase with underscores (snake_case). This convention distinguishes them from class names, which use CapWords. Following this guideline ensures consistency and readability across Python codebases.

The other options suggest styles that are either not recommended (camelCase, CapWords) or misapply the constant convention to attributes.

Exam trap

The trap here is assuming that methods and attributes should mirror the class name's CapWords style, when PEP 8 explicitly reserves that for classes and uses snake_case for members.

9
Multi-Selecteasy

Which TWO of these are valid PEP 8 recommendations for whitespace?

Select 2 answers
A.Use two spaces for every level of indentation.
B.Use large blocks of whitespace between functions.
C.Avoid trailing whitespace.
D.Use tabs for all indentation.
E.Use a single space after commas.
AnswersC, E

Trailing whitespace is invisible but flagged by linters and version-control diffs, so PEP 8 explicitly advises removing it. This satisfies the stem's requirement for a valid whitespace recommendation, as the guideline applies to every line of code regardless of context, making it one of the two correct choices.

Why this answer

Option C is correct because PEP 8 explicitly states that trailing whitespace should be avoided anywhere in code, since it is invisible, can cause spurious diffs, and may trigger errors in some tools. Option E is correct because PEP 8 recommends a single space after a comma in expressions and argument lists (e.g., function calls and tuples), which improves readability. Option A is wrong because PEP 8 mandates four spaces per indentation level, not two.

Option B is wrong because PEP 8 advises using blank lines sparingly—typically two blank lines around top-level functions and classes—not large blocks of whitespace. Option D is wrong because PEP 8 recommends spaces over tabs for indentation, and mixing tabs and spaces is explicitly discouraged.

10
MCQhard

You are implementing a custom context manager using a class. Which methods must be implemented to support the 'with' statement?

A.__setup__ and __teardown__.
B.__open__ and __close__.
C.__init__ and __del__.
D.__enter__ and __exit__.
AnswerD

The with statement calls __enter__ on entry, binding its return value to the target, and __exit__ on exit, passing exception details so cleanup and suppression can occur. Both methods are required for a class-based context manager to work.

Why this answer

A context manager requires `__enter__` to set up the resource and `__exit__` to handle cleanup.

11
MCQmedium

You are writing a Python client to consume a REST API. The API documentation states that the server may respond with a 307 Temporary Redirect when a resource has moved temporarily. You need to ensure that your client, built with the 'requests' library, preserves the original HTTP method and body when following such redirects. Which of the following best describes how 'requests' handles a 307 redirect by default?

A.It changes the request method to GET and discards the body.
B.It returns the 307 response directly without following the redirect.
C.It raises a 'TooManyRedirects' exception immediately.
D.It automatically re-sends the request with the same method and body to the new URL.
AnswerD

The 'requests' library, via urllib3, follows 307 redirects by re-issuing the request with the original method and body intact. This is in accordance with RFC 7231, which specifies that a 307 response must not change the request method. Therefore, a POST request remains a POST with its original payload when the client follows the redirect.

Why this answer

When 'requests' encounters a 307 Temporary Redirect, it follows the redirect while preserving the original HTTP method and request body, as mandated by the HTTP specification. This ensures that non-idempotent requests like POST are not inadvertently converted to GET, which could lead to data loss or unintended side effects. The library handles this automatically unless redirects are disabled.

Exam trap

The trap here is assuming that all redirects convert POST to GET, which is true for 301 and 302 in some clients but not for 307.

12
MCQmedium

You are writing a Python script that uses the `socket` module to create a TCP client. After calling `sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)`, which method should you call next to initiate a connection to a remote server at `('example.com', 80)`?

A.sock.listen(5)
B.sock.bind(('example.com', 80))
C.sock.accept()
D.sock.connect(('example.com', 80))
AnswerD

`connect()` is the correct method for a client socket to establish a connection to a remote server. It takes a tuple of the remote address and port. This initiates the TCP three-way handshake and prepares the socket for sending and receiving data, exactly as needed in this scenario.

Why this answer

To connect a TCP client socket to a remote server, you must call the `connect()` method with the server's address and port. The other methods are used in server-side socket programming: `bind()` to associate a local address, `listen()` to enable incoming connections, and `accept()` to accept them. Thus, `connect()` is the only correct step for a client.

Exam trap

The trap here is confusing client-side and server-side socket methods, especially thinking `bind()` is needed before connecting on a client.

13
MCQmedium

A developer is documenting a function `fetch_records` that accepts a database connection, a table name, and an optional limit. The team follows Google Style Python Docstrings. Which approach correctly documents the parameters and their types?

A.List each parameter under an `Args:` section with the parameter name, a colon, and a description that includes the expected type.
B.Use a `Parameters:` section modeled on reStructuredText field lists with `:param name:` and `:type name:` entries.
C.Describe parameters only in inline `#` comments next to each function call in the calling code.
D.Embed the parameter details directly in the first summary line so readers see them immediately.
AnswerA

Google Style Python Docstrings use an `Args:` section where each parameter is written as `name (type): description`. This format is machine-readable by tools such as Sphinx's napoleon extension and is the documented convention. Including the type in parentheses alongside the name keeps the documentation consistent and parseable for `fetch_records`.

Why this answer

Google Style Python Docstrings document parameters in an `Args:` section using the pattern `name (type): description`. This structured format is parsed by documentation tools and keeps type information alongside the parameter name. Other styles, such as Sphinx field lists or unstructured summaries, do not match the convention the team has adopted, so consistency requires the `Args:` form.

Exam trap

The trap here is conflating Sphinx field-list syntax with Google Style, even though both are valid documentation approaches in different ecosystems.

14
MCQmedium

You are preparing a Python module for PyPI. Your project layout is: project_root/ ├── setup.py ├── src/ │ └── mypackage/ │ ├── __init__.py │ └── core.py └── tests/ └── test_core.py You want to write a test that imports mypackage.core and verifies the function add(a, b). Which import statement should you use at the top of tests/test_core.py to follow best practices for a src-layout project after installing the package in editable mode?

A.from mypackage import core
B.from src.mypackage import core
C.import core
D.import src.mypackage.core as core
AnswerA

With a src layout, the package is installed (e.g., pip install -e .) before running tests, so the package is importable by its top-level name. Importing 'mypackage.core' directly reflects the installed package structure, avoids path manipulation, and ensures tests run against the installed code rather than relative files. This is the recommended practice to prevent accidental imports from the source tree.

Why this answer

In a src-layout project, the package is installed into the environment (e.g., editable install) before tests are run, so tests should import the package by its top-level name, not via the src directory. Using 'from mypackage import core' ensures the test exercises the installed code, matches how users will import it, and avoids fragile sys.path assumptions. This aligns with packaging best practices for test isolation.

Exam trap

The trap here is assuming that because the source files live under src/, the import path must include src, confusing filesystem layout with the importable package name after installation.

15
MCQmedium

Which module provides a high-level API for working with URLs, such as parsing and unparsing them?

A.requests
B.urllib.parse
C.socket
D.http.client
AnswerB

urllib.parse supplies urlparse, urlunparse, urljoin and quote, giving a high-level interface for splitting URLs into components and reassembling them. It directly satisfies the stem's parsing and unparsing requirement, whereas urllib.request handles fetching and urllib.error handles exceptions.

Why this answer

The 'urllib.parse' module is designed for splitting and joining URL components.

16
Multi-Selectmedium

Which TWO of the following exceptions might be raised during socket operations?

Select 2 answers
A.ImportError
B.ValueError
C.TimeoutError
D.KeyError
E.ConnectionRefusedError
AnswersC, E

TimeoutError arises from socket operations when a blocking call exceeds its configured timeout, satisfying the stem's requirement for exceptions raised during socket operations. It is raised by methods such as `recv()`, `accept()` and `connect()` after `settimeout()` elapses, making it a genuine socket-related exception rather than an unrelated error.

Why this answer

TimeoutError (option C) is correct because socket operations that use a timeout (e.g., after calling socket.settimeout() or when a connect/recv/send exceeds the configured timeout) raise socket.timeout, which is an alias/subclass of TimeoutError in Python 3.10+. ConnectionRefusedError (option E) is correct because when a client attempts to connect to a host/port where no process is listening, the TCP RST response causes the OS to report ECONNREFUSED, which Python surfaces as ConnectionRefusedError (a subclass of OSError). The other options do not belong: ImportError (A) relates to module import failures, ValueError (B) is a generic value/argument error not specific to socket I/O, and KeyError (D) arises from missing dictionary keys, none of which are raised by socket operations themselves.

17
MCQeasy

What is the purpose of the logging.StreamHandler?

A.To write logs to a file.
B.To send logs to a stream like stdout.
C.To format log messages.
D.To rotate log files.
AnswerB

StreamHandler writes formatted log records to any file-like stream object, defaulting to sys.stderr but commonly pointed at sys.stdout. It satisfies the stem's requirement of directing log output to a stream, unlike FileHandler, which always opens a named file on disk.

Why this answer

It sends log messages to a stream, such as sys.stderr or sys.stdout.

18
MCQeasy

Which of the following describes the purpose of the __slots__ attribute in a class?

A.To allow private attribute access.
B.To define the method resolution order.
C.To improve performance and reduce memory usage.
D.To prevent inheritance.
AnswerC

__slots__ declares a fixed set of instance attributes, replacing the per-instance __dict__ with a compact slot descriptor array. This removes dictionary overhead, reducing memory usage per object and speeding attribute access, which is the stated purpose of defining __slots__.

Why this answer

__slots__ restricts the creation of new instance attributes and reduces memory footprint by preventing the creation of a per-instance __dict__.

19
MCQmedium

A developer defines a class `Temperature` that stores a Celsius value in `self._celsius` and exposes a `celsius` property with a setter that validates the value is not below absolute zero. After instantiating `t = Temperature(20)`, the developer runs `t.celsius = -300`. What happens?

A.The setter runs, detects the invalid value, and raises a ValueError; `t._celsius` remains 20.
B.A TypeError is raised because `t.celsius` is read-only once the property is defined without a deleter.
C.The assignment silently succeeds and `t.celsius` returns -300 because properties only intercept reads, not writes.
D.Python bypasses the setter because `_celsius` is a private attribute and assigns -300 directly to `t._celsius`.
AnswerA

Assigning to `t.celsius` invokes the property's setter function, which contains the validation logic. Since -300 is below absolute zero, the setter raises ValueError before modifying `self._celsius`, so the attribute keeps its previous value of 20. This is the intended use of properties to enforce invariants on attribute assignment.

Why this answer

The property setter is invoked on assignment to `t.celsius`, and its validation logic rejects -300. Because the exception is raised before `self._celsius` is updated, the original value remains intact. This demonstrates how properties enforce encapsulation and invariants without changing the public attribute name.

Exam trap

The trap here is assuming that a leading underscore on the backing attribute causes Python to bypass the property setter during assignment.

20
MCQhard

You are implementing a custom Tkinter widget that must validate user input in an Entry field and prevent non-numeric characters from being entered. Which mechanism should you use to intercept and optionally reject each keystroke before it modifies the Entry contents?

A.Use entry.config(state='readonly') and toggle it in a '<FocusIn>' handler.
B.Bind '<Key>' to a handler that deletes the last character if it is not a digit.
C.Bind '<KeyRelease>' to a handler that checks the Entry contents and calls entry.delete(0, tk.END) if invalid.
D.Register a validation function with entry.config(validate='key', validatecommand=(vcmd, '%P')) and return True or False from it.
AnswerD

Tkinter's validation mechanism with validate='key' calls the registered command before each insertion or deletion. The %P substitution provides the prospective value of the Entry after the edit. Returning True accepts the change and False rejects it, which is exactly the behaviour needed to block non-numeric input at the source.

Why this answer

Tkinter's built-in validation support is designed for exactly this purpose. Configuring validate='key' with a validatecommand that receives the %P substitution lets the callback inspect the prospective Entry value and return True to accept or False to reject the edit. This intercepts input before it is applied, which is more reliable than post-hoc key bindings that must undo changes.

Exam trap

The trap here is relying on Key or KeyRelease bindings to filter input, when those run after the default insertion and cannot cleanly prevent a character from being entered.

21
Multi-Selecteasy

Which TWO of the following represent common data formats used for REST API request/response payloads?

Select 2 answers
A.XML
B.Plain text only
C.SQL queries
D.JSON
E.Binary-encoded images
AnswersA, D

XML is a widely used REST payload format, employing tag-based markup to structure data with attributes and nested elements. It satisfies the stem's requirement for a common REST API data format, alongside JSON. Its verbosity and schema support suit enterprise integrations, though JSON has largely overtaken it for modern lightweight APIs.

Why this answer

XML (A) is correct because REST APIs commonly use it as a structured, self-describing payload format, typically with the Content-Type application/xml or text/xml, and many frameworks support XML serialization/deserialization. JSON (D) is correct because it is the most widely used REST payload format, with Content-Type application/json, offering lightweight key-value and array structures that map easily to objects in most languages. The unmarked options do not belong: plain text only (B) is not a structured data format for typical REST payloads, SQL queries (C) are database commands rather than a payload serialization format, and binary-encoded images (E) are media content, not a common structured data format for REST request/response bodies.

22
MCQhard

A Tkinter application has a modal dialog implemented as a Toplevel that collects a numeric discount. The dialog's OK button command calls a validator that may raise ValueError, and you want the dialog to stay open with an inline error label rather than crashing the mainloop. The dialog is opened from the main window with dialog.grab_set() followed by main_window.wait_window(dialog). Which approach correctly keeps the error visible and prevents the exception from propagating out of the Tkinter callback?

A.Move the validation into a separate thread and call dialog.destroy() from that thread when validation fails.
B.Call dialog.wait_window(dialog) again inside the OK button command so the dialog blocks until validation succeeds.
C.Wrap the validation logic in try/except ValueError inside the OK button's command, update an error Label's text, and return normally so the callback ends without raising.
D.Set dialog.protocol('WM_DELETE_WINDOW', lambda: None) so the dialog cannot be closed while validation is pending.
AnswerC

Tkinter invokes widget callbacks from the Tcl interpreter, and an uncaught Python exception in a callback is reported through Tkinter's report_callback_exception hook rather than terminating mainloop. Catching ValueError inside the command lets you set the error Label and return normally, so the dialog remains open and the user can correct the input. This is the intended pattern for inline validation in modal Toplevel dialogs.

Why this answer

Inline validation in a modal Toplevel requires the callback to handle its own exceptions and update widget state instead of letting the error escape into Tkinter's global handler. Catching ValueError, writing to the error Label, and returning normally keeps the dialog alive and interactive, which is exactly what the scenario demands. Threading, nested wait_window, and protocol overrides all miss that central point.

Exam trap

The trap here is believing that an exception in a Tkinter callback will crash the application, when it is actually routed to report_callback_exception and the dialog simply fails to show the intended error.

23
MCQmedium

You are designing a plugin system where each plugin class must automatically register itself with a central registry when defined, without requiring an explicit decorator or registration call. You decide to use the __init_subclass__ hook in the base Plugin class. Which statement correctly describes how to implement this so that every subclass is registered with its own class object?

A.Define __init_subclass__ as an instance method in the base class that receives self and uses type(self) to identify the subclass.
B.Override __new__ in the base class to intercept subclass creation and register the subclass there.
C.Use a metaclass with a __call__ method that registers the class when the first instance is created.
D.Define __init_subclass__ as a classmethod in the base class that receives the new subclass as its first argument and adds it to a registry list.
AnswerD

When a subclass is created, Python automatically calls the parent's __init_subclass__ with the new class as the first argument. Defining it as a classmethod in the base class lets you capture that class and append it to a registry, achieving automatic registration without decorators.

Why this answer

The __init_subclass__ hook is invoked automatically on the parent class whenever a subclass is defined, receiving the new subclass as an argument. Implementing it as a classmethod in the base Plugin class allows the base to append each subclass to a shared registry at definition time, satisfying the automatic registration requirement without decorators or manual calls.

Exam trap

The trap here is assuming __init_subclass__ must be explicitly decorated or that it runs on instances rather than on the parent class during subclass creation.

24
Multi-Selectmedium

Which TWO of the following events are commonly bound in Tkinter for mouse interaction?

Select 2 answers
A.<Enter>
B.<Button-1>
C.<Quit>
D.<KeyPress>
E.<MouseMove>
AnswersA, B

`<Enter>` fires when the pointer crosses into a widget's boundary, satisfying the mouse-interaction requirement. Tkinter binds it to the widget under the cursor, generating `<Enter>` on entry and `<Leave>` on exit — distinct from `<Return>`, which is a keyboard event for the Enter key.

Why this answer

In Tkinter, <Enter> (option A) is a standard event that fires when the mouse pointer enters a widget, making it a common mouse-interaction binding. <Button-1> (option B) is also standard and fires when the left mouse button is pressed over a widget, so it is directly a mouse interaction event. By contrast, <Quit> (option C) is not a Tkinter event at all; quitting is typically handled via protocols like WM_DELETE_WINDOW or a command callback. <KeyPress> (option D) is a valid Tkinter event but it is a keyboard event, not a mouse event. <MouseMove> (option E) is not a valid Tkinter event name; mouse motion is bound using <Motion> (or <B1-Motion> for motion while the left button is held).

Exam trap

PCPP1 often tests whether candidates recognize Tkinter's exact event pattern names, so plausible-sounding but non-existent events like <MouseMove> or <Quit> tempt candidates who assume naming conventions from other GUI toolkits.

25
MCQeasy

Which magic method is responsible for providing the informal string representation of an object, typically used for user-facing output?

A.__str__
B.__format__
C.__unicode__
D.__repr__
AnswerA

`__str__` returns the informal, human-readable string representation, which `print()` and `str()` invoke for user-facing output. The alternative `__repr__` targets developers and aims for an unambiguous, ideally evaluable representation. The stem's constraint — informal, user-facing display — maps directly onto `__str__`, making it the responsible magic method.

Why this answer

The __str__ method is used for informal, readable string representations, whereas __repr__ is for formal, unambiguous representations.

26
MCQmedium

You are developing a Python application that must parse a large XML file and extract specific data. The file is too large to fit into memory, so you need to process it incrementally. Which approach using the xml.etree.ElementTree module is most appropriate?

A.Use xml.etree.ElementTree.fromstring() to parse the file in chunks by reading it line by line and passing each line to fromstring().
B.Use xml.etree.ElementTree.parse() to load the entire file into memory and then iterate over the elements.
C.Use xml.etree.ElementTree.XMLParser() with a custom target to build the tree incrementally, then process the tree.
D.Use xml.etree.ElementTree.iterparse() to iterate over the file and process elements as they are parsed, clearing them from memory afterwards.
AnswerD

iterparse() provides an incremental parser that yields events for start and end of elements. By processing elements and then clearing them using element.clear() or removing them from the root, you can keep memory usage low. This is the recommended approach for large XML files. It allows you to handle data as it is parsed without loading the entire document into memory.

Why this answer

iterparse() is designed for incremental parsing of large XML files. It generates events as it parses, allowing you to process elements and then clear them to free memory. This keeps memory usage bounded and is the standard way to handle large XML with ElementTree.

The other options either load the entire file into memory or are not suited for incremental parsing.

Exam trap

The trap here is confusing iterparse() with other parsing methods like parse() or fromstring(); iterparse() is the only one that supports incremental, memory-efficient parsing.

27
MCQmedium

Which magic method allows an object to behave like a function?

A.__apply__
B.__invoke__
C.__func__
D.__call__
AnswerD

Defining `__call__` on a class makes its instances callable, so `obj()` invokes that method directly — the exact behaviour the stem requires. Python resolves the call on the instance rather than the class, letting the object behave like a function while retaining its own state.

Why this answer

The __call__ method enables an object to be invoked with parentheses syntax.

28
MCQmedium

You are writing a client that must upload a binary file to a REST endpoint using requests.put(). The file is several hundred megabytes, and you want to avoid loading it entirely into memory while still letting the server know the total size. Which approach meets both goals?

A.Read the file with open(path, 'rb').read() and pass the resulting bytes to the data argument.
B.Encode the file with base64 and pass the result as a JSON string in the json argument.
C.Pass the file path string directly as the data argument so requests opens it on your behalf.
D.Open the file in binary mode and pass the file object as the data argument, optionally setting the Content-Length header explicitly.
AnswerD

Passing an open binary file object streams the contents to the socket in chunks rather than reading it all at once, keeping memory use low. Setting Content-Length explicitly informs the server of the total size, which is useful when the server requires it or when chunked transfer is undesirable.

Why this answer

Supplying an open binary file object as data lets requests stream the body in chunks, avoiding a full in-memory copy, and an explicit Content-Length header communicates the total size. Reading bytes, passing a path string, or base64-encoding into JSON all either consume large memory or send the wrong payload format.

Exam trap

The trap here is assuming data accepts a filename or that reading the file first is harmless, when the parameter expects content or a stream and full reads defeat streaming.

29
MCQhard

When using the place() geometry manager, what is the purpose of 'relx' and 'rely'?

A.Relative position as a float from 0 to 1.
B.Relative font size.
C.Relative pixel coordinates.
D.Relative Z-index for layering.
AnswerA

relx and rely express widget placement as a float between 0.0 and 1.0, representing a fraction of the master's width and height. This satisfies the stem's relative positioning requirement, unlike absolute x and y, which use pixel offsets.

Why this answer

In Tkinter's place() geometry manager, relx and rely specify the widget's position as a fraction of the parent's width and height, expressed as a float between 0.0 and 1.0. For example, relx=0.5 centers the widget horizontally regardless of the window's actual pixel size. This makes layouts resolution-independent, unlike absolute x/y coordinates.

Exam trap

PCPP1 often tests whether candidates confuse relx/rely (fractional, 0.0–1.0) with the absolute x/y pixel options, or mistakenly associate them with font scaling or Z-order.

How to eliminate wrong answers

Option B is wrong because relative font size is controlled through font specifications (e.g., font=('Helvetica', 12)) or widget scaling, not through relx/rely, which are purely positional. Option C is wrong because relative pixel coordinates are not what relx/rely represent — pixel offsets are given by the absolute x and y options, while relx/rely are fractional proportions of the parent. Option D is wrong because Z-order layering in Tkinter is handled by lift()/lower() and stacking order, not by relx/rely, which only affect placement.

30
Multi-Selectmedium

Which THREE of the following are attributes of the 'requests.Response' object?

Select 3 answers
A.socket
B.text
C.status_code
D.connect()
E.json()
AnswersB, C, E

The text attribute holds the response body decoded into a string using the charset from the Content-Type header, falling back to apparent encoding. It is a property of requests.Response, distinct from content, which returns undecoded bytes.

Why this answer

Option B (text) is correct because requests.Response.text returns the response body decoded into a Unicode string using the encoding inferred from the HTTP headers or apparent encoding. Option C (status_code) is correct because requests.Response.status_code holds the integer HTTP status code (e.g., 200, 404) returned by the server. Option E (json()) is correct because requests.Response.json() is a method that deserializes the response body from JSON into Python objects (dict/list), raising a JSONDecodeError if parsing fails.

Option A (socket) is not a documented attribute of Response; the underlying socket is managed by urllib3 and accessed via raw/connection internals, not as a direct Response attribute. Option D (connect()) is not a Response method; connect() belongs to HTTPAdapter/urllib3 connection handling, not to the Response object.

31
MCQmedium

A developer writes a class `Money` that implements `__eq__` to compare amounts and currencies, but does not implement `__hash__`. Instances of `Money` are then used as keys in a `set`. What is the result?

A.Instances are hashed using the hash of their `__dict__`, so two equal `Money` objects collapse into one set element.
B.The set stores instances by identity, so duplicates are allowed and no error occurs.
C.Instances can be added to a set, and equality is used for deduplication because `__hash__` defaults to `id()`-based hashing.
D.A TypeError is raised when adding an instance to the set because the class is unhashable.
AnswerD

Defining `__eq__` without `__hash__` causes Python to set `__hash__ = None` on the class, marking instances as unhashable. Any attempt to use them in a set or as a dict key raises TypeError: unhashable type. To fix this, the developer must explicitly define `__hash__`, typically based on the same attributes used in `__eq__`.

Why this answer

Python disables the inherited `__hash__` when a class overrides `__eq__`, because equal objects must have equal hashes for hash-based collections to work correctly. The developer must define `__hash__` explicitly, hashing the same attributes used in `__eq__`, so that equal `Money` instances produce identical hashes and can be stored in sets or dicts.

Exam trap

The trap here is assuming that overriding `__eq__` leaves the default identity-based `__hash__` in place so instances remain usable in sets.

32
MCQeasy

A Python script consumes a REST endpoint that returns a JSON document. You call response = requests.get(url) and want to convert the body into native Python objects. The response is guaranteed to be valid JSON. Which expression gives you the deserialized data?

A.response.json()
B.response.content
C.response.text
D.json.load(response)
AnswerA

The json method on a Response decodes the body using the json module and returns the corresponding Python object, such as a dict or list. It is the direct, idiomatic way to deserialize a JSON API response and raises a clear error if the body is not valid JSON.

Why this answer

A requests Response exposes a json method that parses the body with the standard library's JSON decoder and returns native Python types. The text and content attributes expose the body as a string or bytes respectively, and json.load expects a file-like object, so none of those directly yield deserialized data.

Exam trap

The trap here is confusing the raw body accessors text and content with the parsing method json, which is the only one that returns Python objects.

33
MCQmedium

In the Factory pattern, what should you do if the requested type is unknown?

A.Log the error and return the base class.
B.Raise a ValueError.
C.Return a default instance.
D.Return None.
AnswerB

An unrecognised type string means the factory cannot construct a valid product, so silently returning None would defer failure. Raising ValueError signals the invalid argument immediately at the call site, letting callers handle the unsupported request explicitly.

Why this answer

Raising a ValueError or a custom 'UnknownTypeException' is the standard way to handle invalid inputs in a factory.

34
MCQeasy

When using configparser, how do you retrieve a value as a boolean?

A.parser.get('section', 'option', type=bool)
B.parser.get_bool('section', 'option')
C.parser.getboolean('section', 'option')
D.bool(parser.get('section', 'option'))
AnswerC

getboolean applies configparser's boolean conversion, accepting values such as 'yes', 'no', 'true', 'false', 'on', 'off' and '1'/'0', and raising ValueError for anything else. get() would return the raw string, leaving type conversion to your own code.

Why this answer

The getboolean() method converts common truthy/falsy values automatically.

35
MCQhard

A developer is reviewing a pull request where a function uses a global variable to track a counter. The reviewer suggests refactoring to avoid global state. Which refactoring best follows best practices for maintainability and testability?

A.Pass the counter as an argument and return the updated value.
B.Use a default mutable argument to store the counter.
C.Use a module-level variable and declare it global inside the function.
D.Encapsulate the counter in a class and use an instance variable.
AnswerD

Encapsulating the counter in a class with an instance variable removes global state, making the code more modular and testable. Each instance maintains its own counter, and the state is explicit. This aligns with object-oriented best practices and reduces side effects, improving maintainability.

Why this answer

Encapsulating state in a class instance eliminates global mutable state, making the code more modular and testable. Each instance has its own counter, and interactions are explicit. Passing the counter as an argument is also valid but can be less convenient for complex state.

Using module-level globals or mutable defaults perpetuates the issues of shared state.

Exam trap

The trap here is thinking that using a module-level variable with global is equivalent to encapsulation, but it still introduces global mutable state and its associated problems.

36
MCQmedium

You are developing a Tkinter application that includes a Button widget. When the user clicks the button, you need to execute a function named handle_click that accepts no arguments. Which approach correctly associates this function with the button's click event?

A.button = Button(root, text='Click', command='handle_click')
B.button = Button(root, text='Click', command=lambda: handle_click)
C.button = Button(root, text='Click', command=handle_click)
D.button = Button(root, text='Click', command=handle_click())
AnswerC

Passing the function name without parentheses assigns the function object itself as the command callback. Tkinter stores this callable and invokes it each time the button is clicked, which is the correct way to bind a handler. This approach works for any callable that takes no arguments, and it is the standard pattern for Tkinter event handling.

Why this answer

The command option of a Tkinter Button expects a callable object that will be invoked when the button is clicked. Passing the function name without parentheses provides that callable. Using parentheses calls the function immediately, a lambda that returns the function does not call it, and a string is not callable.

Therefore, the only correct approach is to pass the function object itself.

Exam trap

The trap here is confusing function invocation with function reference, leading to immediate execution or no execution at all.

37
MCQeasy

In the 'requests' library, which HTTP method is typically used to update an existing resource on a server?

A.PUT
B.POST
C.GET
D.DELETE
AnswerA

PUT replaces the entire target resource representation at its URI, making it the standard method for full updates. PATCH performs partial modification, while POST typically creates a new subordinate resource rather than updating an existing one.

Why this answer

The PUT method is standard for replacing or updating an existing resource at a specific URI.

38
MCQhard

You are implementing a `Vector` class whose instances should support `v1 + v2` and also `v1 + 5`, where the second form broadcasts the scalar across every component. A colleague suggests relying on `__radd__` to handle the scalar case. Why is that insufficient?

A.`__radd__` receives the operands in the same order as `__add__`, so it cannot distinguish which operand is the vector and which is the scalar.
B.`__radd__` is reserved for augmented assignment, so `v1 += 5` would work while `v1 + 5` would raise a `TypeError` regardless of what `__add__` returns.
C.`__radd__` is only invoked for subclasses of the left operand's type, so a plain `int` on the left can never trigger it under any circumstances.
D.`__radd__` is only consulted when the left operand's `__add__` returns `NotImplemented` or does not exist, so `Vector.__add__` must first detect and return `NotImplemented` for unsupported operand types.
AnswerD

Python evaluates `v1 + 5` by calling `Vector.__add__(v1, 5)` first. Only if that returns the `NotImplemented` singleton does the interpreter try `int.__radd__(5, v1)`. Therefore `__radd__` cannot intercept the scalar case unless `__add__` explicitly yields `NotImplemented`, making a cooperative `__add__` essential to the design.

Why this answer

Binary operator dispatch tries the left operand's forward method first. For `v1 + 5`, that is `Vector.__add__`, which must return the `NotImplemented` singleton to signal that it cannot handle an `int`. Only then does Python attempt the reflected operation.

Relying on `__radd__` alone leaves `__add__` free to raise or misbehave, so the two methods must be designed as a pair.

Exam trap

The trap here is believing `__radd__` is tried first or independently, when it only runs after the left operand's forward method returns `NotImplemented`.

39
MCQhard

You are designing a Python class that manages a database connection. The class has a method `_execute_query` that should only be used internally. According to Python best practices and PEP 8, how should you indicate that this method is for internal use only?

A.Prefix the method name with a single underscore: `_execute_query`.
B.Prefix the method name with two underscores: `__execute_query`.
C.Use the `@internal` decorator from the `typing` module.
D.Add a comment above the method: `# Internal use only`.
AnswerA

PEP 8 recommends using a single leading underscore to indicate that a method or attribute is intended for internal use. This is a convention that tells other developers that the method is not part of the public API, though it can still be accessed. It is the standard way to signal internal use in Python.

Why this answer

PEP 8 specifies that a single leading underscore should be used to indicate that an attribute or method is intended for internal use. This is a widely recognized convention in Python. Double underscores are for name mangling, comments are not a convention, and there is no standard `@internal` decorator.

Exam trap

The trap here is confusing the single underscore (internal use) with the double underscore (name mangling) or assuming that a decorator or comment is the standard way.

40
MCQhard

A teammate writes a `Money` value object that defines `__eq__` to compare amounts and currencies, and `__hash__` to hash the same two fields. During a code review you notice that a subclass `Discount` adds a `percentage` field, overrides only `__eq__` to include that field, and leaves `__hash__` inherited. Objects of `Discount` are then used as dictionary keys. What is the actual runtime consequence?

A.Python raises a `SyntaxError` at class-definition time because overriding `__eq__` without also overriding `__hash__` is statically rejected by the compiler.
B.The dictionary works correctly because `dict` uses `id()`-based hashing for user-defined classes whenever `__hash__` is ambiguous, sidestepping the overridden `__eq__`.
C.The inherited `Money.__hash__` is used, and because it hashes only amount and currency, two `Discount` objects with different percentages but equal amount and currency collide into one dictionary entry.
D.Because `Discount` defines `__eq__`, Python sets `Discount.__hash__` to `None` in that class, so instances become unhashable and dictionary insertion raises `TypeError`.
AnswerD

When a class defines `__eq__` without defining `__hash__`, Python implicitly sets that class's `__hash__` attribute to `None`, regardless of any `__hash__` inherited from a base class. Instances of `Discount` therefore cannot be hashed, and using one as a dictionary key raises `TypeError: unhashable type`. The inherited `Money.__hash__` does not save the subclass from this rule.

Why this answer

Python enforces an invariant between equality and hashing: if a class overrides `__eq__`, the default identity hash is no longer consistent with the new equality, so the interpreter sets `__hash__` to `None` in that class. Defining `__eq__` in `Discount` without a matching `__hash__` makes its instances unhashable, and inheritance from `Money` does not restore hashability. Dictionary keys must therefore be plain `Money` objects or the subclass must define its own `__hash__`.

Exam trap

The trap here is assuming that a `__hash__` inherited from a base class remains in effect after a subclass redefines `__eq__`.

41
MCQmedium

What is the difference between a class-level variable and an instance-level variable?

A.Instance-level variables cannot be modified.
B.Class-level variables are always constant.
C.Class-level variables are hidden from subclasses.
D.Class-level variables are shared by all instances.
AnswerD

Class-level variables live on the class object itself and are therefore shared across every instance, whereas instance-level variables are stored per object in its __dict__. Assignment through an instance shadows rather than mutates the class attribute.

Why this answer

A class-level variable is shared across all instances of the class, whereas an instance-level variable is specific to each object.

42
Multi-Selecthard

Which TWO of the following are valid ways to add padding to a widget in the grid layout?

Select 2 answers
A.margin=10
B.spacing=10
C.gap=10
D.padx=10
E.pady=10
AnswersD, E

padx=10 is a valid grid() keyword that inserts ten pixels of horizontal padding around the widget within its cell. The stem asks for padding options, and padx is one of the two accepted grid padding parameters, alongside pady.

Why this answer

In Tkinter's grid geometry manager, external padding around a widget is set with the padx and pady options, so option D (padx=10) adds 10 pixels of horizontal padding and option E (pady=10) adds 10 pixels of vertical padding to the widget's cell. These are the standard grid() parameters for per-widget padding, e.g., widget.grid(row=0, column=0, padx=10, pady=10). Option A (margin=10) is not a recognized Tkinter geometry option, and option B (spacing=10) is not a valid grid() parameter either.

Option C (gap=10) is likewise not a Tkinter grid option; internal padding between widgets in a container is instead controlled by the container's padx/pady or by grid's ipadx/ipady for internal widget padding, not by a 'gap' keyword.

43
MCQmedium

When creating a new project, how should you structure your imports?

A.In the order they are used in the file.
B.Standard library imports, then third-party, then local, with blank lines between groups.
C.Alphabetically regardless of source.
D.All in a single line separated by semicolons.
AnswerB

PEP 8's import grouping convention satisfies the readability constraint by separating standard library, third-party and local imports with blank lines, so each dependency's origin is immediately clear and merge conflicts or circular-import confusion are easier to spot.

Why this answer

PEP 8 specifies that imports should be grouped in the order: standard library, related third-party, then local application/library imports, with a blank line between each group. Within each group, imports should be sorted alphabetically. This convention makes dependencies explicit and helps detect circular imports early.

Exam trap

PCPP1 often tests whether candidates know PEP 8's specific grouping order (standard, third-party, local) rather than just 'alphabetical' or 'usage order' — the grouping is the key detail.

How to eliminate wrong answers

Option A is wrong because ordering imports by usage order is not a recognized convention and makes it harder to see at a glance which dependencies are external vs. internal. Option C is wrong because alphabetical ordering across all sources ignores the semantic distinction between standard library, third-party, and local imports — PEP 8 requires grouping first, then alphabetical within groups. Option D is wrong because semicolon-separated imports on a single line violate PEP 8 (which discourages multiple statements per line) and reduce readability; each import should be on its own line.

44
MCQmedium

What is the purpose of the 'socket.shutdown()' method in Python?

A.It forces the socket to release its memory
B.It resets the socket connection immediately
C.It stops further communication on the socket
D.It closes the file descriptor completely
AnswerC

shutdown() disables further send or receive operations on the socket, optionally in one direction, without closing the file descriptor. This satisfies the stem by halting communication while leaving the socket object itself intact for later close().

Why this answer

shutdown() allows you to stop sending or receiving data on a socket while keeping the file descriptor open.

45
MCQhard

You are using the `json` module to serialize a custom object that contains a `datetime.date` attribute. When you call `json.dumps(obj)`, you get a `TypeError: Object of type date is not JSON serializable`. Which approach correctly allows serialization while preserving the date as an ISO 8601 string?

A.Create a subclass of `json.JSONEncoder` and override its `default` method to return `obj.isoformat()` for `date` instances, then pass it to `json.dumps` via the `cls` parameter.
B.Implement a `__json__` method on the custom object that returns a serializable dictionary, and `json.dumps` will call it automatically.
C.Use `json.dumps(obj, default=str)` to automatically convert any non-serializable object to its string representation.
D.Convert the `date` attribute to a string using `obj.date.isoformat()` before calling `json.dumps`, and then convert it back when deserializing.
AnswerA

The `json` module allows customization through a `JSONEncoder` subclass. Overriding the `default` method lets you define how to serialize unsupported types like `date`. Returning `obj.isoformat()` produces an ISO 8601 string. Passing the class via `cls` to `json.dumps` instructs the encoder to use it. This is the standard, extensible solution.

Why this answer

The `json` module's `JSONEncoder` class provides a `default` method that is called for objects that are not natively serializable. By subclassing and overriding this method, you can return a serializable representation, such as an ISO 8601 string for dates. Passing this encoder class to `json.dumps` via the `cls` argument enables the custom behavior.

Exam trap

The trap here is assuming that the `json` module has built-in support for `datetime` objects or that a special method like `__json__` is automatically invoked, when in fact you must explicitly provide a custom encoder or default function.

46
MCQmedium

You are designing a class `Matrix` that supports element-wise addition and scalar multiplication. You want `m1 + m2` to return a new `Matrix` without modifying `m1` or `m2`. You have implemented `__add__` correctly. A colleague writes `m1 += m2` and expects `m1` to be rebound to a new `Matrix` object. However, after the statement, `m1` still refers to the same object and its internal data has been modified in place. Which change to your class is the most likely cause of this behavior?

A.You defined `__iadd__` to call `__add__` and then return `self` after updating the internal list in place.
B.You defined `__iadd__` to return a new `Matrix` instance without modifying `self`.
C.You defined `__radd__` to return a new `Matrix` instance instead of `NotImplemented`.
D.You defined `__add__` to modify `self` in place and return `self`.
AnswerA

Defining `__iadd__` overrides the fallback to `__add__` for the `+=` operator. If `__iadd__` mutates the instance and returns `self`, the name `m1` is rebound to the same object, and its internal state changes. This exactly matches the observed behavior.

Why this answer

The augmented assignment `+=` first looks for `__iadd__` on the left operand. When `__iadd__` is defined and mutates the object before returning `self`, the name is rebound to the same object and the original data changes. Without `__iadd__`, Python falls back to `__add__`, which produces a new object and rebinds the name.

Exam trap

The trap here is assuming that `+=` always behaves like `+` and rebinds to a new object, overlooking that defining `__iadd__` can make augmented assignment mutate in place.

47
MCQmedium

When overriding the __getattr__ method, what must you be careful to avoid?

A.Infinite recursion by accessing non-existent attributes.
B.Raising AttributeError.
C.Accessing class attributes.
D.Calling super().__getattr__.
AnswerA

Accessing a missing attribute inside `__getattr__` re-invokes `__getattr__`, because the attribute lookup fails again, producing infinite recursion until Python raises `RecursionError`. Guard by raising `AttributeError` for unknown names or delegating to `super().__getattr__()`, satisfying the stem's requirement to avoid this pitfall.

Why this answer

Infinite recursion occurs if you try to access an attribute inside __getattr__ that does not exist, triggering __getattr__ again.

48
MCQeasy

You are writing a script that reads a large CSV file using csv.reader. The file uses a semicolon as the delimiter and contains quoted fields with embedded newlines. Which instantiation correctly handles this format?

A.csv.reader(file, delimiter=';', quoting=csv.QUOTE_NONE)
B.csv.reader(file, delimiter=';', quotechar='"')
C.csv.reader(file, delimiter=',', quotechar='"')
D.csv.reader(file, delimiter=';', escapechar='\\')
AnswerB

The csv.reader accepts delimiter and quotechar parameters. Setting delimiter to ';' matches the file's separator, and quotechar to '"' allows proper parsing of quoted fields, including those containing embedded newlines. This is the correct and sufficient configuration for the described format.

Why this answer

The csv.reader requires the correct delimiter and quotechar to parse a file with semicolon-separated values and quoted fields containing newlines. Setting delimiter to ';' and quotechar to '"' ensures that embedded newlines within quotes are treated as part of the field. Disabling quoting or using the wrong delimiter breaks parsing, and an escapechar alone does not address quoted newlines.

Exam trap

The trap here is assuming that an escapechar or quoting mode can replace the quotechar for handling embedded newlines, when in fact the quotechar is essential for the csv module to recognize quoted fields.

49
MCQeasy

When receiving data from a TCP socket using 'recv(buffer_size)', what does the returned value represent?

A.A boolean indicating connection status
B.The data as a byte string
C.The total number of bytes in the stream
D.The number of packets received
AnswerB

recv() returns the bytes actually received, up to buffer_size, as a bytes object — not a decoded string, count, or address. This byte-string value is what the caller must decode or process, satisfying the scenario's need to know what the return represents.

Why this answer

The method returns the bytes received, up to the specified buffer size.

50
Multi-Selecthard

Which THREE of the following steps are required to initialize a TCP server socket?

Select 3 answers
A.Create a socket with socket.AF_INET and socket.SOCK_STREAM
B.Call connect() to start the server
C.Call listen() to enable incoming connections
D.Call recv() before bind()
E.Call bind() to associate with an address and port
AnswersA, C, E

Creating the socket with `AF_INET` and `SOCK_STREAM` is the mandatory first step: it allocates an IPv4 TCP endpoint before any binding or listening can occur. Without this stream socket, `bind()` and `listen()` have no file descriptor to operate on, so the server cannot accept connections.

Why this answer

Option A is correct because a TCP server must first create a stream socket using socket.AF_INET for IPv4 addressing and socket.SOCK_STREAM for TCP, which establishes the endpoint that will later be bound and listened on. Option C is correct because after binding, the server must call listen() to put the socket into passive mode so it can accept incoming connection requests, which is what makes it a listening server socket. Option E is correct because bind() associates the socket with a specific local IP address and port, which is required before the socket can listen for connections on that address.

Option B is incorrect because connect() is used by a client to initiate a connection to a server, not by a server to start listening. Option D is incorrect because recv() is used to receive data on an already-connected socket and cannot be called before bind() during server initialization.

Exam trap

PCPP1 often tests whether candidates confuse client-side calls (connect, recv) with server-side initialization steps (socket, bind, listen), catching those who mix up the two roles.

51
Multi-Selectmedium

Which TWO practices help maintain clean code when using Python's 'try-except' blocks?

Select 2 answers
A.Keep the 'try' block as small as possible.
B.Use a single 'except:' clause for the whole project.
C.Always ignore errors in the 'except' block.
D.Catch the most specific exceptions first.
E.Put as much code as possible in the 'try' block.
AnswersA, D

Keeping the `try` block minimal confines exception handling to the exact statement that may fail, so unrelated errors are not accidentally caught and masked. This satisfies the stem's clean-code constraint by making the guarded operation explicit, narrowing the exception's scope, and preventing broad handlers from hiding genuine bugs elsewhere in the logic.

Why this answer

Option A is correct because keeping the 'try' block as small as possible limits it to only the statements that can actually raise the expected exception, which makes the source of an error obvious and prevents unrelated bugs from being accidentally caught and masked. Option D is correct because Python evaluates 'except' clauses in order, so catching the most specific exception classes first (for example 'except ValueError:' before 'except Exception:') ensures precise handling and prevents a broad handler from shadowing a more specific one. Option B is wrong because a single bare 'except:' for the whole project swallows every exception, including 'KeyboardInterrupt' and 'SystemExit', and hides real defects.

Option C is wrong because silently ignoring errors in the 'except' block discards diagnostic information and lets the program continue in an invalid state. Option E is wrong because putting as much code as possible in the 'try' block widens the scope of what can be caught, making it unclear which statement raised the exception and increasing the chance of masking unrelated errors.

52
MCQmedium

You are writing a Python application that must parse a configuration file where a value spans multiple lines, such as a long list of email addresses separated by newlines. You decide to use the configparser module. Which of the following correctly describes how to include a multi-line value in the configuration file?

A.Indent continuation lines with whitespace; they will be joined with newline characters.
B.Separate lines with a semicolon to indicate continuation.
C.Enclose the value in triple quotes to allow multiple lines.
D.Use a backslash at the end of each line to indicate continuation.
AnswerA

In configparser, multi-line values are created by indenting subsequent lines. The parser joins these lines with newline characters, preserving them as part of the value. This allows you to store lists or long strings without additional escaping. The indentation must be consistent and deeper than the key's indentation. This behavior is documented and widely used for configuration files like setup.cfg.

Why this answer

In configparser, multi-line values are specified by indenting continuation lines. The parser then joins these lines with newline characters. This is the standard way to include values that span multiple lines, such as lists.

The other options incorrectly suggest backslashes, triple quotes, or semicolons, which are not part of the INI format syntax for continuation.

Exam trap

The trap here is assuming that Python-like line continuation (backslash) or string literal syntax (triple quotes) applies to configparser files.

53
MCQmedium

A developer creates a class named `Registry` in a module. The class inherits from `ABCMeta` and defines a `__new__` method that performs validation on the class namespace before the class is created. Inside `__new__`, the developer needs to inspect the attributes defined in the class body of the class being created. Which parameter of `__new__` provides direct access to those attributes?

A.The `bases` parameter.
B.The `**kwargs` parameter.
C.The `namespace` parameter.
D.The `mcls` parameter.
AnswerC

In `ABCMeta.__new__(mcls, name, bases, namespace, **kwargs)`, the fourth positional parameter is the namespace dictionary containing all attributes defined in the class body. Accessing it before calling `super().__new__` lets the developer validate or modify attributes during class creation, exactly matching what the scenario requires.

Why this answer

The namespace dictionary is the fourth positional argument supplied to `ABCMeta.__new__`. It holds every name bound in the class body before the class object exists, which is exactly the data needed for validation during class creation. The other parameters describe the metaclass, the parent tuple, or extra keywords, none of which carry class-body attributes.

Exam trap

The trap here is confusing the metaclass `__new__` signature parameters, assuming `bases` or `mcls` carries the class body attributes.

54
MCQhard

You are building a Tkinter GUI that includes a Canvas widget. You want to draw a rectangle and then later change its fill color without redrawing the entire canvas. Which method should you use to update the rectangle's fill color?

A.rectangle.fill('blue')
B.canvas.create_rectangle(..., fill='blue')
C.canvas.itemconfig(rectangle_id, fill='blue')
D.canvas.config(fill='blue')
AnswerC

The itemconfig method (or itemconfigure) allows you to modify the options of an existing canvas item by its ID. Passing the rectangle's ID and the new fill color updates only that item, leaving other canvas elements untouched. This is efficient and preserves the item's other properties. It is the correct way to dynamically change a canvas item's appearance after creation.

Why this answer

Canvas items are managed by the Canvas widget and are referenced by integer IDs. To change an item's options after creation, you use canvas.itemconfig with the item ID and the new option values. Recreating the item adds a new one, configuring the canvas itself does not affect items, and items are not Python objects with methods.

Thus, itemconfig is the correct method.

Exam trap

The trap here is assuming canvas items are objects with methods or that recreating them updates the original.

55
MCQmedium

When sending a JSON payload with 'requests.post()', which argument should you use to automatically set the 'Content-Type' to 'application/json'?

A.data=json.dumps(payload)
B.json=payload
C.params=payload
D.body=payload
AnswerB

Passing `json=payload` serialises the dictionary and sets the `Content-Type` header to `application/json` automatically, satisfying the stem's requirement to avoid manual header configuration. The `data=` argument would instead send a form-encoded body, leaving the content type unset or incorrect.

Why this answer

The 'json' argument automatically serializes the data and sets the correct headers.

56
MCQeasy

When using 'requests.get()', how can you include a custom HTTP header in your request?

A.Use the 'data' argument
B.Pass it as part of the URL string
C.Use the 'headers' dictionary argument
D.Use the 'params' dictionary
AnswerC

Passing a dictionary to the `headers` argument lets `requests.get()` merge those key-value pairs into the outgoing HTTP request, satisfying the requirement to send a custom header. Each key becomes a header field name and each value its content, so `requests.get(url, headers={'X-Custom': 'value'})` transmits it directly.

Why this answer

The 'headers' parameter accepts a dictionary of HTTP headers.

57
MCQmedium

When using a metaclass, how can you access the class attributes during the class definition?

A.By calling super().
B.By accessing the class __dict__.
C.By querying the base class.
D.By accessing the namespace dictionary passed to __new__.
AnswerD

During class creation the metaclass's __new__ receives the namespace dictionary containing all attributes defined in the class body, so reading it there exposes them before the class object exists. __init__ receives the already-built class instead, making __new__ the correct hook.

Why this answer

The class dictionary passed to the metaclass's __new__ method contains all the attributes defined within the class body.

58
MCQhard

You are building a canvas-based drawing tool and need to detect when the user clicks on a specific rectangle item to select it, while other clicks should be ignored. Which canvas feature should you use?

A.Call itemconfigure() on the rectangle with an activefill option to detect selection.
B.Bind <Button-1> to the top-level window and use the focus() method to determine which item was clicked.
C.Use the canvas tag_bind() method to bind <Button-1> to the rectangle's tag or item id.
D.Bind a <Button-1> handler to the canvas and compare event coordinates against the rectangle's bounding box.
AnswerC

tag_bind() associates an event binding with a tag or a specific item id, so the callback fires only when the pointer interacts with that item. This leverages the canvas's built-in hit testing and respects overlapping items according to display order. It is the intended way to make individual canvas items interactive, and it automatically follows the item if it is moved, since the binding is tied to the item rather than to fixed coordinates.

Why this answer

Canvas items support their own event bindings through tag_bind(), which ties a callback to a tag or item id. When the user clicks, the canvas performs hit testing and invokes the binding only if the pointer is over a matching item, honoring stacking order for overlaps. This is more robust than comparing raw coordinates and automatically tracks items as they move or change, making it the correct choice for selecting individual shapes.

Exam trap

The trap here is assuming that a canvas-wide <Button-1> binding with manual coordinate checks is necessary, when tag_bind() already provides item-level hit testing.

59
MCQmedium

A Tkinter data-entry form uses an Entry widget for a numeric amount. Users report that pressing Enter in the Entry does nothing, and the value is only saved when they click a separate Save button. You want Enter to trigger the same save routine as the button, without duplicating logic. Which binding achieves this?

A.entry.bind('<KeyPress>', lambda event: save_amount())
B.entry.bind('<Enter>', lambda event: save_amount())
C.entry.bind('<FocusOut>', lambda event: save_amount())
D.entry.bind('<Return>', lambda event: save_amount())
AnswerD

The <Return> sequence corresponds to the Enter key on the main keyboard, and binding it on the Entry invokes the handler whenever that widget has focus. Using a lambda that calls the existing save_amount function reuses the same logic as the Save button, so there is no duplication. The event parameter is accepted and ignored, which is fine for a simple trigger.

Why this answer

The <Return> event sequence is the correct Tkinter binding for the Enter key on an Entry widget. Binding it to a small lambda that calls the existing save function reuses the button's logic and gives users the keyboard shortcut they expect. KeyPress is too broad, Enter refers to pointer entry, and FocusOut triggers on focus changes rather than the Enter key.

Exam trap

The trap here is confusing the <Enter> event, which fires when the mouse pointer enters a widget, with the <Return> event sequence generated by the Enter key.

60
MCQhard

You are logging events with custom levels. How do you add a custom level 'TRACE' (value 5) to the logging module?

A.logging.TRACE = 5
B.logging.setLevel('TRACE', 5)
C.logging.addLevelName(5, 'TRACE')
D.logging.define_level('TRACE', 5)
AnswerC

logging.addLevelName() registers a numeric level with its name in the module's internal name-to-level mapping, so records logged at 5 render as 'TRACE'. This is the documented API for introducing custom levels without subclassing or patching internals.

Why this answer

You use logging.addLevelName() to associate a numerical value with a level name.

61
MCQmedium

What is the recommended way to handle a function that requires a large number of arguments?

A.Just define the function with many arguments; it is perfectly fine.
B.Use a single argument dictionary.
C.Use *args and **kwargs for everything.
D.Group related parameters into a dataclass or object.
AnswerD

Grouping related parameters into a dataclass or object reduces the positional argument count, satisfying the stem's constraint of a function requiring a large number of arguments. It also improves readability and keeps the call signature stable as related values evolve together.

Why this answer

If a function has too many arguments, it is often a sign it should be broken down or that a configuration object should be used.

62
MCQmedium

You need to send binary data over a socket. Which method should you use on the socket object to ensure all data is sent?

A.write()
B.sendall()
C.send()
D.recv()
AnswerB

`sendall()` loops internally until every byte is handed to the socket buffer, so it satisfies the stem's requirement that all binary data be sent. Unlike `send()`, which may transmit only part of the payload and return a byte count, `sendall()` raises an exception on failure and returns `None`.

Why this answer

The sendall() method continues to transmit data from the buffer until all data has been sent or an error occurs.

63
MCQhard

You are developing a multithreaded HTTP scraper. When using the 'requests' library inside 'threading.Thread' objects, what is the recommended practice for handling session persistence?

A.Initialize a new Session object inside each thread's run method
B.Wrap the session object in a threading.Lock
C.Share a single global Session object across all threads
D.Disable connection pooling using 'pool_connections=0'
AnswerA

A Session is not thread-safe, so sharing one across threads risks corrupted connection-pool state. Creating a Session inside each thread's run method gives every thread its own pool and cookie jar, satisfying the stem's session-persistence requirement without cross-thread contention.

Why this answer

The requests.Session object is not thread-safe because it maintains shared state such as cookies, connection pools, and headers. Initializing a new Session inside each thread's run method ensures each thread has its own isolated session, avoiding race conditions and data corruption. This is the recommended practice for multithreaded scraping with requests.

Exam trap

PCPP1 often tests whether candidates assume requests.Session is thread-safe and can be shared globally, when in fact it must be instantiated per thread to avoid state corruption.

How to eliminate wrong answers

Option B is wrong because wrapping a shared Session in a threading.Lock would serialize all HTTP requests, eliminating the concurrency benefit and still risking subtle state issues; it is not the recommended pattern. Option C is wrong because sharing a single global Session across threads is unsafe due to concurrent mutation of cookies, headers, and connection pool state, leading to unpredictable behavior. Option D is wrong because disabling connection pooling with pool_connections=0 does not address thread safety and would degrade performance by forcing new connections per request.

64
MCQeasy

You are creating a class where you want to prevent instances from having a __dict__ to save memory. You add __slots__ = ('x', 'y') to the class. Which statement is true about this class?

A.The class can still accept arbitrary attributes, but they will be stored in a separate dictionary.
B.Instances will still have a __dict__, but x and y will be stored in slots for faster access.
C.Subclasses of this class will also be prevented from having a __dict__ automatically.
D.Instances of the class will not have a __dict__ and can only have attributes x and y.
AnswerD

Defining __slots__ with 'x' and 'y' tells Python to allocate space for exactly those attributes in a compact structure, and the instance __dict__ is not created. Attempting to assign any other attribute raises AttributeError. This reduces memory overhead per instance.

Why this answer

The __slots__ declaration restricts instances to the named attributes and eliminates the per-instance __dict__, saving memory. Only attributes listed in __slots__ can be assigned; others raise AttributeError. Subclasses do not automatically inherit this restriction unless they also define __slots__.

Exam trap

The trap here is assuming subclasses automatically inherit the no-__dict__ behavior, when they must declare __slots__ themselves to maintain it.

65
MCQeasy

According to PEP 257, what is the standard format for a single-line docstring?

A.Use a single quote for the entire block.
B.The docstring should span three lines including the summary.
C.The summary should start on the next line.
D.Use triple quotes and keep the summary on the same line, ending with a period.
AnswerD

PEP 257 specifies triple double quotes with the summary on the same line as the opening quotes, terminated by a period. This satisfies the stem's single-line format requirement, keeping the docstring concise and consistent with the convention.

Why this answer

A single-line docstring should be on the same line as the opening triple quotes, ending with a period.

66
Multi-Selectmedium

Which TWO of the following are true regarding multiple inheritance in Python?

Select 2 answers
A.It is not supported.
B.super() is used for cooperative method calls.
C.The MRO is determined at runtime.
D.It uses the C3 linearization algorithm.
E.Multiple inheritance is always preferred over composition.
AnswersB, D

super() follows the MRO, delegating to the next class in the linearised chain rather than a fixed parent, which enables cooperative multiple inheritance. Each class calls super() so sibling branches all execute exactly once, satisfying the stem's requirement for a true statement about multiple inheritance.

Why this answer

Option B is correct because in Python's multiple inheritance, super() does not simply call the parent class but follows the Method Resolution Order to invoke the next class in the chain, enabling cooperative multiple inheritance where each class's method calls super() to pass control along the MRO. Option D is correct because Python resolves the method resolution order for multiple inheritance using the C3 linearization algorithm, which produces a consistent, monotonic ordering that respects local precedence and subclass relationships. Option A is incorrect because Python explicitly supports multiple inheritance, allowing a class to inherit from several base classes.

Option C is incorrect because the MRO is computed at class creation time (when the class is defined), not dynamically at runtime for each method call. Option E is incorrect because composition is often preferred over multiple inheritance for maintainability and avoiding the diamond problem; multiple inheritance is not always preferred.

67
MCQhard

You are implementing a class `Vector` that supports addition and scalar multiplication. You want `v1 + v2` to return a new `Vector`, and `v1 * 3` to return a new scaled `Vector`. You also want `3 * v1` to work identically. Which pair of methods must you implement to support both `v1 * 3` and `3 * v1` correctly, assuming `v1` is a `Vector` and `3` is an `int`?

A.`__rmul__` and `__radd__`
B.`__mul__` only, because Python automatically swaps operands.
C.`__mul__` and `__rmul__`
D.`__mul__` and `__imul__`
AnswerC

`__mul__` handles `v1 * 3` because the left operand is a `Vector`. For `3 * v1`, Python first tries `int.__mul__(3, v1)`, which returns `NotImplemented` because `int` does not know how to multiply by a custom type. Python then calls `Vector.__rmul__(v1, 3)`. Implementing both ensures both orders work and return a new `Vector`.

Why this answer

To support both `v1 * 3` and `3 * v1`, the class must define `__mul__` for the normal case and `__rmul__` for the reflected case. When the left operand's `__mul__` returns `NotImplemented`, Python tries the right operand's `__rmul__`. Implementing both ensures consistent behavior regardless of operand order, which is important for intuitive mathematical types.

Exam trap

The trap here is believing that defining `__mul__` alone is enough because Python will reorder operands automatically.

68
MCQmedium

A Tkinter application has a main window containing a Text widget used as a log console. The application performs a long-running data import and must remain responsive, so the import runs in a background thread. The worker thread needs to append status lines to the Text widget. Which approach is correct?

A.Wrap each insert call in a threading.Lock shared with the main thread so only one thread touches the Text widget at a time.
B.Have the worker thread place messages on a queue.Queue, and have the main thread poll that queue periodically using the after method and perform the insert calls.
C.Call the Text widget's insert method directly from the worker thread, since Tkinter serializes widget access internally.
D.Call the root window's update_idletasks method from the worker thread before each insert so pending events are processed first.
AnswerB

The queue acts as the only shared object between threads, and the main thread retrieves messages through a scheduled after callback, so every widget operation occurs on the thread that owns the Tcl interpreter. This keeps the interface responsive because the main thread never blocks on the import, and it avoids the undefined behavior of cross-thread widget calls. It is the standard, safe pattern for Tkinter multithreading.

Why this answer

Tkinter widgets may only be manipulated from the thread that created the root window, so a background worker must not touch the Text widget directly. Passing messages through a queue and having the main thread drain it with an after-scheduled callback keeps all widget calls on the owning thread while the import proceeds in parallel. This preserves responsiveness and avoids interpreter corruption.

Exam trap

The trap here is believing that locks or internal serialization make Tkinter widget calls safe from any thread, when the real constraint is that only the thread owning the Tcl interpreter may drive widgets.

69
MCQmedium

You are designing a class hierarchy for a document processing system. The base class `Document` defines a method `render()` that returns a string. You want subclasses to be forced to provide their own implementation, and you want to prevent `Document` from being instantiated directly. Which code correctly enforces this requirement?

A.class Document: def render(self): raise NotImplementedError("Subclass must implement render") def __init__(self): if self.__class__ is Document: raise TypeError("Cannot instantiate Document directly")
B.from abc import ABC, abstractmethod class Document(ABC): @abstractmethod def render(self): pass
C.class Document: def render(self): pass def __new__(cls, *args, **kwargs): if cls is Document: raise TypeError("Cannot instantiate Document directly") return super().__new__(cls)
D.class Document: def render(self): raise Exception("Not implemented") class DocumentMeta(type): def __call__(cls, *args, **kwargs): if cls is Document: raise TypeError("Cannot instantiate Document directly") return super().__call__(*args, **kwargs)
AnswerB

Using ABC and @abstractmethod makes Document uninstantiable and forces subclasses to implement render() before they can be instantiated. This is the standard, explicit way to define an abstract base class in Python. Any subclass that does not override render() remains abstract and raises TypeError on instantiation, precisely matching the requirement to force implementation and prevent direct instantiation.

Why this answer

The abstract base class pattern with ABC and @abstractmethod is the idiomatic way to prevent direct instantiation of a base class and force subclasses to implement specific methods. It ensures that any subclass lacking an override remains abstract and cannot be instantiated, raising a TypeError. The other approaches either fail to enforce implementation or rely on fragile runtime checks.

Exam trap

The trap here is assuming that raising NotImplementedError in a method is equivalent to an abstract method, when it only fails at call time rather than preventing instantiation.

70
MCQeasy

In the context of the CSV module, what is a 'dialect'?

A.A specific file extension.
B.A set of parameters defining a CSV format.
C.The encoding of the file.
D.A list of column names.
AnswerB

A dialect groups formatting parameters — delimiter, quotechar, quoting, line terminator, escapechar — that together describe one CSV variant. Passing a dialect to reader or writer applies that whole parameter set, which is exactly the definition the stem requests.

Why this answer

A dialect is a grouping of parameters (delimiter, quotechar, etc.) that defines the format of a CSV file.

71
MCQeasy

You are writing a Python script that needs to parse a URL and extract the query parameters. The URL is 'https://api.example.com/v1/items?limit=10&offset=20'. Which module should you use to reliably parse this URL and retrieve the value of 'limit'?

A.urllib.parse
B.urllib.request
C.requests
D.urlparse
AnswerA

The urllib.parse module provides functions like urlparse and parse_qs to break a URL into components and parse the query string into a dictionary. Using urlparse on the URL and then parse_qs on the query component will yield {'limit': ['10'], 'offset': ['20']}. This is the standard and reliable way to parse URLs in Python, handling encoding and edge cases correctly.

Why this answer

The urllib.parse module is specifically designed for parsing URLs. It provides urlparse to split a URL into scheme, netloc, path, query, etc., and parse_qs to parse the query string into a dictionary. This is the correct and standard way to extract query parameters like 'limit' from a URL in Python.

Exam trap

The trap here is confusing urllib.parse with urllib.request, or thinking that urlparse is a standalone module, when it is actually a function within urllib.parse.

72
MCQhard

How do you access the value of a StringVar associated with an Entry widget?

A.var.retrieve()
B.var.content()
C.var.get()
D.var.value
AnswerC

Calling `get()` on the `StringVar` retrieves its current contents, which mirror the Entry widget's text because the two are bound together. This satisfies the stem's requirement to access the variable's value directly, rather than querying the widget itself via `Entry.get()`.

Why this answer

The get() method is used on the StringVar object to retrieve its current value.

73
MCQeasy

Which status code indicates that a requested resource has been successfully created?

A.201 Created
B.400 Bad Request
C.200 OK
D.204 No Content
AnswerA

HTTP 201 Created confirms the request succeeded and a new resource now exists at the location given in the response's Location header. This satisfies the stem's requirement for the status code signalling successful resource creation.

Why this answer

HTTP status code 201 Created indicates that the request has succeeded and has led to the creation of a new resource. It is typically returned in response to a POST or PUT request that creates a resource, and the response often includes a Location header pointing to the new resource. This is the standard, RFC 7231-defined code for successful resource creation.

Exam trap

PCPP1 often tests the confusion between 200 OK and 201 Created, since both indicate success; candidates must remember that 201 specifically signals resource creation, not just a successful response.

How to eliminate wrong answers

Option B is wrong because 400 Bad Request indicates the server cannot process the request due to client error (e.g., malformed syntax), not successful creation. Option C is wrong because 200 OK is a generic success code indicating the request succeeded but does not specifically signal resource creation. Option D is wrong because 204 No Content indicates success with no body to return, typically used for DELETE or PUT updates, not for creating a resource that should be referenced.

74
MCQhard

What is the primary risk of using 'getattr' without a default value?

A.It returns None.
B.It enters an infinite loop.
C.It raises an AttributeError.
D.It creates the attribute.
AnswerC

Without a default, getattr raises AttributeError when the named attribute is absent from the object. That unhandled exception is the primary risk, since callers must anticipate and catch it rather than receiving a fallback value.

Why this answer

If the attribute is not found, it raises an AttributeError, potentially crashing the application if not handled.

75
MCQhard

You are developing a Tkinter application that uses multiple threads to perform background tasks. One thread updates a Label widget's text using its config method. Occasionally, the application crashes with a Tcl error about calling from a different thread. What is the correct approach to safely update the GUI from a background thread?

A.Use the after method to schedule the update on the main thread.
B.Directly call the widget's config method from the background thread; Tkinter handles thread safety internally.
C.Use a lock (threading.Lock) around the widget update to prevent concurrent access.
D.Call update_idletasks() before updating the widget from the background thread.
AnswerA

The after method can be used to schedule a function to run in the main event loop. By calling after from the background thread, you can pass a callback that performs the GUI update. This ensures the update occurs in the main thread, avoiding thread safety issues. This is the recommended approach for thread-safe GUI updates.

Why this answer

Tkinter is not thread-safe; all GUI updates must occur in the main thread. To safely update a widget from a background thread, you should use the after method to schedule a callback that performs the update. This callback runs in the main event loop.

Other approaches like using locks or update_idletasks do not address the fundamental thread safety issue. Direct calls from background threads are unsafe.

Exam trap

The trap here is assuming that Tkinter is thread-safe or that using locks can make it safe, but the only safe way is to schedule updates on the main thread.

Page 1 of 4

Page 2

All pages