Courseiva

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

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

Page 2

Page 3 of 4

Page 4
151
MCQmedium

A code reviewer notices that a Python module defines a class named `dataProcessor` and a function named `processData`. The team follows PEP 8. Which naming convention should be applied to the class name?

A.Rename the class to `data_processor` using snake_case.
B.Keep the class name as `dataProcessor` (camelCase).
C.Rename the class to `DATA_PROCESSOR` using all uppercase with underscores.
D.Rename the class to `DataProcessor` using CapWords (PascalCase).
AnswerD

PEP 8 states that class names should normally use the CapWords convention (also known as PascalCase), where each word starts with an uppercase letter and there are no underscores. Renaming `dataProcessor` to `DataProcessor` aligns with this widely accepted standard, improving readability and consistency across Python codebases. This is the correct convention for classes.

Why this answer

PEP 8 recommends CapWords (PascalCase) for class names, so `DataProcessor` is the correct choice. Snake_case, camelCase, and all-uppercase with underscores are used for other purposes: functions/variables, non-standard style, and constants respectively. Adhering to this convention ensures consistency and readability in Python projects.

Exam trap

The trap here is assuming that any consistent naming style is acceptable, but PEP 8 specifically mandates CapWords for classes.

152
Multi-Selectmedium

Which THREE of the following are valid parameters for the pack() layout manager?

Select 3 answers
A.row
B.expand
C.column
D.side
E.fill
AnswersB, D, E

The `expand` parameter accepts a Boolean value that allocates surplus space to a widget when its parent is resized, stretching it along the packing direction. This satisfies the stem's requirement for a genuine `pack()` argument, unlike geometry options belonging to `grid()` or `place()`.

Why this answer

The pack() geometry manager accepts the expand option (B), a Boolean that tells pack to allocate extra space in the parent container to the widget, letting it grow when the window is resized. It also accepts the side option (D), which specifies the edge against which the widget is packed — values are TOP (default), BOTTOM, LEFT, and RIGHT. The fill option (E) is valid as well, controlling whether the widget stretches to fill its allocated parcel; its values are NONE, X, Y, or BOTH.

Options A (row) and C (column) are not pack() parameters — they belong to the grid() geometry manager, where row and column specify the cell coordinates for a widget.

153
MCQhard

You are designing a Python microservice that exposes a REST API. A client sends a PUT request to update a resource with a JSON body. Your service must ensure idempotency: if the same request is received multiple times, the resource should end up in the same state. Which HTTP method and semantics should you implement to guarantee idempotency for updates?

A.Use POST because it can carry a body and is commonly used for updates, and implement a custom idempotency key header to detect duplicates.
B.Use PATCH because it allows partial updates, and implement versioning to prevent duplicate changes.
C.Use PUT because it replaces the entire resource with the request payload, and repeating the same PUT results in the same final state.
D.Use GET with a query parameter that contains the new state, because GET is safe and idempotent.
AnswerC

PUT is defined as idempotent: sending the same request multiple times has the same effect as sending it once, because it replaces the resource with the provided representation. This matches the requirement to guarantee idempotency for updates without additional application-level duplicate detection. The server should treat the payload as the complete new state of the resource.

Why this answer

PUT is the HTTP method specifically designed for idempotent updates: it replaces the target resource with the request payload, so repeating the same request yields the same state. POST and PATCH do not inherently guarantee idempotency, and GET must not be used for updates. Implementing PUT correctly ensures that duplicate requests do not cause unintended side effects.

Exam trap

The trap here is confusing idempotency with safety or assuming that any method with a body can be made idempotent with headers.

154
MCQmedium

You are writing a library that expects a custom exception. Which practice aligns best with Python's exception handling hierarchy?

A.Use a mixin class without inheritance.
B.Inherit from StandardError.
C.Inherit from BaseException.
D.Inherit from Exception.
AnswerD

Inheriting from Exception satisfies the requirement that a custom exception integrates with Python's standard hierarchy, so `except Exception` handlers still catch it. Unlike BaseException subclasses, which bypass ordinary handlers, this keeps the library's errors catchable by callers while avoiding the overly broad BaseException branch.

Why this answer

Custom application exceptions should inherit from Exception, which is the base class for all non-system-exiting exceptions and is intended for user-defined errors. Inheriting from Exception ensures the exception is caught by normal 'except Exception' handlers and does not interfere with interpreter-level control flow. This is the standard practice recommended by PEP 8 and the Python documentation.

Exam trap

PCPP1 often tests the Python 2 vs Python 3 exception hierarchy — candidates who remember 'StandardError' from Python 2 pick it, not realizing it was removed in Python 3.

How to eliminate wrong answers

Option A is wrong because a mixin without inheritance does not create an exception class at all — it would not be raisable or catchable as an exception. Option B is wrong because StandardError was a Python 2 class that was removed in Python 3; referencing it causes a NameError. Option C is wrong because BaseException is reserved for system-exiting exceptions like SystemExit, KeyboardInterrupt, and GeneratorExit — inheriting from it means normal 'except Exception' blocks will not catch your custom exception, which is almost never desired.

155
MCQeasy

Which magic method is triggered when an object is deleted using the 'del' keyword?

A.__clear__
B.__del__
C.__remove__
D.__destroy__
AnswerB

`__del__` is the destructor magic method invoked when an object's reference count reaches zero or the interpreter shuts down, satisfying the stem's requirement for deletion via `del`. Note that `del` removes a reference rather than guaranteeing immediate finalisation, so `__del__` may run later under cyclic references.

Why this answer

The __del__ method is called when the object's reference count reaches zero.

156
MCQhard

What is the result of applying the @staticmethod decorator to a method inside a class that also defines a metaclass?

A.The metaclass must manually convert it back to a static method.
B.It raises a TypeError at class definition time.
C.The method is correctly bound as a static function regardless of the metaclass.
D.The metaclass will treat the method as an instance method.
AnswerC

The `@staticmethod` decorator wraps the function in a descriptor that returns the plain function without binding `self` or `cls`, so metaclass interference is irrelevant. Metaclasses control class creation, not instance attribute lookup, so the static method resolves correctly on both the class and its instances.

Why this answer

The @staticmethod decorator creates a static method object which is stored in the class dictionary; it is independent of the metaclass's __init__ logic for instance methods.

157
MCQmedium

You are developing a Tkinter application with a top-level window that contains a Frame widget. Inside the Frame, you place three Button widgets using grid(). Later, you need to add a fourth Button that should span the full width of the Frame, below the existing three. Which grid() configuration should you apply to the new Button?

A.button.grid(row=3, column=0, columnspan=3, sticky='ns')
B.button.grid(row=3, column=0, columnspan=3, sticky='nsew')
C.button.grid(row=0, column=3, rowspan=3, sticky='ns')
D.button.grid(row=3, column=0, columnspan=3, sticky='ew')
AnswerD

Using row=3 places the button in the next available row, column=0 starts at the first column, columnspan=3 makes it occupy all three columns, and sticky='ew' stretches it horizontally to fill the frame width, achieving the desired full-width span.

Why this answer

To place a widget below existing grid-managed widgets and have it span the full width, you must specify the next row, start at column 0, set columnspan to the number of columns to cover, and use sticky='ew' to stretch horizontally. The other options either misplace the widget or stretch it in the wrong direction.

Exam trap

The trap here is confusing rowspan with columnspan or using sticky='nsew' when only horizontal expansion is needed.

158
MCQhard

You are writing a reusable module that must expose only a small public API while keeping several helper functions and constants internal. Users of the module should not import the helpers with 'from mymodule import *', but direct access such as mymodule._helper() may still be needed for tests. Which approach fits best?

A.Rename every helper with a leading underscore and omit __all__ entirely.
B.Define __all__ listing only the public names and leave helper names unchanged.
C.Place the helpers in a nested class and expose them as static methods of that class.
D.Rename every helper with a leading underscore and define __all__ listing only the public names.
AnswerD

A leading underscore signals that a name is non-public, and defining __all__ controls exactly which names 'from mymodule import *' brings in, so helpers stay out of star imports while remaining directly accessible for tests. This combination is the documented convention for shaping a module's public surface without hiding implementation entirely. It satisfies both the API restriction and the testing requirement.

Why this answer

Marking implementation details with a leading underscore communicates that they are non-public, while __all__ explicitly defines which names a star import exports. Because __all__ only affects star imports, the underscored helpers remain directly accessible as attributes for unit tests. This pairing gives a precise, documented public API without making the internals unreachable.

Exam trap

The trap here is believing that __all__ makes names private, when it only filters what a star import copies into the caller's namespace.

159
MCQeasy

You are writing a Python script that needs to create a temporary directory, write several files into it, and ensure that the directory and its contents are automatically deleted when the script exits, even if an exception occurs. Which approach using the tempfile module is most appropriate?

A.Use tempfile.gettempdir() to obtain the system temporary directory and create a subdirectory there, relying on the operating system to clean it up.
B.Use tempfile.mkdtemp() to create the directory and manually delete it in a finally block.
C.Use tempfile.TemporaryDirectory() as a context manager; the directory and its contents are removed when the context exits.
D.Use tempfile.NamedTemporaryFile(delete=True) to create a file, and write all other files into the same directory as that file.
AnswerC

tempfile.TemporaryDirectory() creates a temporary directory and returns an object that can be used as a context manager. Upon exiting the with block, the directory and all its contents are recursively deleted, even if an exception is raised inside the block. This provides automatic, exception-safe cleanup and is the idiomatic solution for the scenario.

Why this answer

The TemporaryDirectory class is specifically designed for this use case. It creates a temporary directory and ensures its complete removal when the context manager exits, regardless of whether an exception occurred. This is the most robust and Pythonic way to handle temporary directories with automatic cleanup, avoiding manual cleanup code and potential resource leaks.

Exam trap

The trap here is confusing mkdtemp with TemporaryDirectory; mkdtemp requires manual cleanup, while TemporaryDirectory handles it automatically via the context manager protocol.

160
MCQmedium

Which widget is most appropriate for displaying a list of selectable items?

A.tk.Checkbutton()
B.tk.Listbox()
C.tk.OptionMenu()
D.tk.Menu()
AnswerB

tk.Listbox() renders a scrollable list of text items and natively supports single or extended selection, satisfying the requirement for selectable items. Unlike read-only display widgets, it tracks a selection index and emits virtual events, making it the direct fit for choosing from a list.

Why this answer

The Listbox widget is intended for displaying a list of strings that the user can select.

161
Multi-Selecthard

Which TWO of these identify a potential 'code smell' in Python exception handling?

Select 2 answers
A.Using 'finally' for cleanup.
B.Swallowing exceptions with an empty 'except' block.
C.Catching specific exceptions.
D.Catching 'BaseException' instead of 'Exception'.
E.Raising custom exceptions.
AnswersB, D

An empty `except:` block catches every exception, including `KeyboardInterrupt` and `SystemExit`, then discards it silently. This hides failures, so bugs surface later far from their origin. It satisfies the stem's code-smell criterion: the handler neither logs, re-raises, nor narrows the exception type, leaving no diagnostic trace.

Why this answer

Option B is a code smell because an empty 'except:' block silently swallows every exception, hiding failures and making debugging nearly impossible; at minimum the handler should log or re-raise. Option D is a code smell because 'BaseException' includes 'SystemExit', 'KeyboardInterrupt', and 'GeneratorExit', so catching it can prevent normal interpreter shutdown and interrupt handling; application code should normally catch 'Exception' or more specific subclasses. Option A is not a smell: 'finally' is the correct construct for guaranteed cleanup such as closing files or releasing locks.

Option C is not a smell: catching specific exception types is the recommended practice for precise, safe error handling. Option E is not a smell: defining and raising custom exceptions improves clarity and lets callers handle domain-specific errors.

162
MCQmedium

You are writing a class `Temperature` that should support addition and comparison. You want `t1 + t2` to return a new `Temperature` object, and `t1 == t2` to compare their values. Which magic methods must you implement to achieve this?

A.__radd__ and __eq__
B.__add__ and __cmp__
C.__iadd__ and __eq__
D.__add__ and __eq__
AnswerD

__add__ is called for the + operator and should return a new Temperature instance. __eq__ is called for == and should compare the underlying values. Implementing these two methods provides the required behavior. Without __add__, + would raise TypeError; without __eq__, == would fall back to identity comparison, which is not desired.

Why this answer

To support the + operator, a class must implement __add__. For equality comparison with ==, it must implement __eq__. These two methods directly correspond to the requested operations.

Other methods like __iadd__ or __radd__ serve different purposes and are not required for the basic behavior described.

Exam trap

The trap here is confusing __add__ with __iadd__ or __radd__, which handle in-place addition and reflected addition respectively, not the standard + operator.

163
MCQeasy

A desktop tool built with Tkinter needs a list of departments shown as mutually exclusive radio buttons. When the user selects a department, the underlying model object's department attribute must update immediately, and the code must read the selection later without iterating over every radio button. Which Tkinter mechanism best satisfies these requirements?

A.Use a ttk.Combobox and call get() on it whenever the model is saved to the database.
B.Give each Radiobutton its own BooleanVar and inspect all of them with cget when the model needs the current department.
C.Use a Listbox configured with selectmode='browse' and read its curselection() to determine the chosen department.
D.Create an IntVar or StringVar, pass it as the variable option to every Radiobutton in the group, and read or trace that variable when the model needs updating.
AnswerD

Radiobuttons sharing a single Tkinter variable form one mutually exclusive group; selecting one sets the variable to that button's value and clears the others automatically. Binding a trace_add callback on the variable pushes changes straight into the model, and reading the variable later requires no widget iteration. This is the idiomatic Tkinter way to keep selection state and application data synchronized.

Why this answer

A shared Tkinter variable is the mechanism that ties a group of Radiobuttons together and makes their selection readable as a single value. Because the variable can be traced, the model updates the moment the user clicks, and later reads need only the variable rather than a loop over widgets. Separate variables, Listboxes, and Comboboxes all fail at least one stated requirement.

Exam trap

The trap here is assuming that each Radiobutton needs its own variable, when in fact a single shared variable is what creates the mutually exclusive group and the convenient read point.

164
MCQmedium

You are using configparser and want to access a value that might not exist, but provide a default value if it is missing. Which method is most appropriate?

A.parser.get('section', 'option', fallback='val')
B.parser.get('section', 'option', default='val')
C.parser.get_or_default('section', 'option', 'val')
D.parser.exists('section', 'option') ? ...
E.parser.get('section', 'option') or 'val'
AnswerA

get() accepts a fallback keyword argument, returning that value instead of raising NoOptionError or NoSectionError when the option or section is absent. This directly satisfies the requirement for a default when the value might not exist.

Why this answer

The get() method accepts a 'fallback' argument to return a default value if the option is missing.

165
MCQmedium

When executing a SQL query with parameters in sqlite3, why should you use placeholders (e.g., ?) rather than f-strings?

A.It is required for SELECT queries only.
B.It enables automatic commit behavior.
C.It is faster to execute.
D.It prevents SQL injection vulnerabilities.
AnswerD

Placeholders send parameter values separately from the SQL text, so sqlite3 treats them purely as data rather than executable syntax. This neutralises SQL injection, satisfying the stem's security constraint: f-strings interpolate untrusted input directly into the statement, letting crafted values alter query structure.

Why this answer

Using placeholders prevents SQL injection attacks and allows the library to handle type conversions.

166
MCQhard

You are writing a Python module that includes a function to compute the factorial of a number. You want to document the function using a docstring that is compatible with the Google Python Style Guide. Which of the following docstrings correctly follows the Google style for documenting parameters and return values, including types?

A."""Compute the factorial of a number. Arguments: n: int, the number to compute the factorial for. Returns: int, the factorial of n. Raises: ValueError, if n is negative. """
B."""Compute the factorial of a number. :param n: The number to compute the factorial for. :type n: int :return: The factorial of n. :rtype: int :raises ValueError: If n is negative. """
C."""Compute the factorial of a number. @param n: The number to compute the factorial for. @return: The factorial of n. @raises ValueError: If n is negative. """
D."""Compute the factorial of a number. Args: n (int): The number to compute the factorial for. Returns: int: The factorial of n. Raises: ValueError: If n is negative. """
AnswerD

This docstring follows the Google style: a one-line summary, then sections for Args, Returns, and Raises. Each parameter is documented with its type in parentheses, and the return type is specified. The Raises section documents the exception. This format is easily parsed by tools like Sphinx with napoleon and is very readable, making it the most compliant with the Google Python Style Guide.

Why this answer

The Google Python Style Guide specifies that docstrings should have sections like Args, Returns, and Raises, with parameter types in parentheses after the parameter name. The correct docstring follows this exactly, making it both human-readable and machine-parsable by tools like Sphinx with the napoleon extension. This consistency is key for maintainable documentation.

Exam trap

The trap here is confusing the Google style with other popular docstring formats like reST or Epydoc, or slightly altering the section headers and type placement, which breaks compatibility with tools expecting the exact Google format.

167
Multi-Selecteasy

Which TWO of the following are valid geometry managers in Tkinter?

Select 2 answers
A.pack
B.block
C.align
D.flow
E.grid
AnswersA, E

'pack' is a genuine Tkinter geometry manager, arranging widgets in blocks against the parent's edges before the next widget. It satisfies the stem by being one of the three valid managers alongside 'grid' and 'place'.

Why this answer

Option A, pack, is a valid Tkinter geometry manager that organizes widgets by packing them against the edges of their parent container in the order they are added. Option E, grid, is also a valid Tkinter geometry manager that places widgets in a two-dimensional table of rows and columns using row and column indices. The other options do not belong: block, align, and flow are not Tkinter geometry managers; Tkinter's third standard geometry manager is place, which is not listed here.

168
MCQhard

What is the effect of setting __slots__ in a parent class on a child class that does not define its own __slots__?

A.The child class will have a __dict__ attribute, overriding the parent's optimization.
B.The child class will raise an error at instantiation.
C.The child class will inherit the memory savings automatically.
D.The child class will be unable to add new attributes.
AnswerA

Omitting __slots__ in the child reinstates a per-instance __dict__, so the parent's memory optimisation no longer applies to child instances. The child still inherits the parent's slot descriptors, but new attributes are stored in the dictionary, satisfying the scenario where the subclass defines no __slots__.

Why this answer

The child class will receive an instance __dict__ unless it also defines __slots__, effectively defeating the memory optimization of the parent.

169
MCQhard

You are using the datetime module to calculate the difference between two dates. You have two datetime objects, start and end, and you need to find the number of full days between them, ignoring any fractional part. Which expression correctly computes this?

A.(end - start).microseconds / 86400000000
B.(end - start).total_seconds() / 86400
C.(end - start).seconds / 86400
D.(end - start).days
AnswerD

Subtracting two datetime objects yields a timedelta object. The .days attribute of a timedelta gives the number of whole days (the integer part) between the two dates, discarding any partial day. This directly provides the number of full days.

Why this answer

Subtracting two datetime objects produces a timedelta object. The .days attribute of a timedelta gives the number of full days between the two dates, as an integer, discarding any partial day. This is the correct way to get the number of whole days.

Other attributes like .seconds and .microseconds represent only the respective components, not the total duration.

Exam trap

The trap here is confusing the .days attribute with total_seconds() or other components, or assuming that .seconds gives total seconds instead of the seconds component.

170
MCQhard

A Tkinter application uses a Canvas to draw a seating chart. Each seat is a rectangle created with create_rectangle, and seats are grouped by section. When a section is selected, every seat in it must change fill color, and some seats must later be moved to a new position. Which strategy best supports efficient grouped updates while keeping individual seats addressable?

A.Delete all rectangles in the section and recreate them with the new color and position whenever a section changes.
B.Assign a unique tag to each seat's rectangle and use the tag to call itemconfig on all seats in the section, and use coords or move to reposition individual seats.
C.Place each seat rectangle inside its own Frame widget and change the Frame background color, relying on the canvas window items to reflect the change.
D.Store each rectangle's item id in a dictionary and iterate over the section, calling itemconfig and coords on each id individually.
AnswerB

Canvas tags let a single itemconfig call recolor every item sharing the tag, so a section update is one operation rather than a loop of per-item calls. Each seat can still carry its own unique tag as well, allowing precise repositioning with coords or move. This design gives both bulk section updates and individual addressability, exactly matching the requirement of grouped recoloring plus selective movement.

Why this answer

Canvas tags are the intended mechanism for applying an operation to many items at once: itemconfig with a tag recolors every matching item in a single call, and each seat can also carry a unique tag for precise coords or move operations. This yields efficient section-wide updates while preserving individual addressability, unlike per-item loops or destructive recreation.

Exam trap

The trap here is treating tags as mere labels for lookups, when their real power is that itemconfig, move, and delete accept a tag and act on every matching item at once.

171
MCQhard

You are using the sqlite3 module to insert a large number of rows into a table. You want to maximize performance by reducing the number of disk writes. Which approach is most effective?

A.Set connection.isolation_level = None and execute each INSERT individually.
B.Use a single transaction by executing BEGIN, then many INSERTs, then COMMIT.
C.Set the connection's isolation_level to 'DEFERRED' and commit after every insert.
D.Create a new cursor for each INSERT statement.
AnswerB

Wrapping many INSERT statements in one transaction reduces the number of fsync operations and disk writes. SQLite commits all changes at once when COMMIT is issued. This is the standard way to speed up bulk inserts. The sqlite3 module allows explicit transaction control via BEGIN/COMMIT or by leaving isolation_level at its default and calling commit() once.

Why this answer

Batching many INSERTs into a single transaction minimizes disk I/O and is the most effective way to speed up bulk inserts in sqlite3. Autocommit or frequent commits increase overhead. Using a single cursor also helps, but the transaction grouping is the key factor.

Exam trap

The trap here is thinking that autocommit mode or frequent commits improve performance, when they actually increase disk writes.

172
MCQmedium

You are maintaining a Tkinter inventory application where users type quantities into an Entry widget. A colleague reports that the application accepts "12.5" for an item that must be a whole number, and invalid keystrokes are only caught after the user clicks Save. You must reject non-numeric input as it is typed, while still allowing a normal editing experience. Which mechanism should you register on the Entry widget?

A.A command callback passed to the Entry widget's validatecommand option, with validate set to "key".
B.A call to the Entry widget's config method with the state option set to "readonly" while the user is typing.
C.A trace callback attached to a StringVar linked to the Entry widget, raising an exception whenever the new value is not an integer.
D.A binding for the <Return> event that inspects the Entry contents and shows a messagebox when the value is not an integer.
AnswerA

Registering a validation callback through validatecommand with validate="key" makes Tkinter invoke the callback on each keystroke, before the character is inserted. Returning False from the callback rejects the edit immediately, so letters or decimal points never appear in the field. This matches the requirement of rejecting invalid input as it is typed rather than only at save time, and it preserves normal cursor and editing behavior.

Why this answer

Tkinter's Entry validation framework invokes a registered callback at defined moments, and validate="key" triggers it on every keystroke before the change is applied. Returning False from that callback cancels the edit, so non-integer characters are rejected immediately while legitimate editing continues to work. This is the only listed approach that prevents bad input from ever reaching the widget, matching the stated requirement.

Exam trap

The trap here is assuming that any callback reacting to typed input can block it, when only the validation callback registered with validatecommand can veto an edit before it happens.

173
Multi-Selecthard

You are building a Tkinter desktop application with a menu bar. Users report two problems: keyboard shortcuts such as Ctrl+S do not trigger the Save command when focus is inside a Text widget, and mnemonic underlines on the File menu are missing. You must correct the menu configuration. Which two changes should you make? (Choose two.)

Select 2 answers
A.Configure the menu entry with state="normal" so keyboard traversal is enabled for the File menu.
B.Bind the <Control-s> event to the save handler on the root window or on the widget that holds focus, in addition to adding the menu entry.
C.Set tearoff=0 on the menubar so the File menu can be detached and the underline becomes visible.
D.Pass accelerator="Ctrl+S" to the Save menu entry so the shortcut text is displayed next to the command.
E.Set underline=0 on the File cascade menu entry so the first character receives a mnemonic underline.
AnswersB, E

Menu accelerators in Tkinter are cosmetic: the displayed text does not install a binding. To make Ctrl+S actually invoke the handler, you must bind the <Control-s> event, typically on the root window or the focused widget, and route it to the save function. This directly addresses the missing behavior users reported when focus is inside the Text widget.

Why this answer

In Tkinter, the accelerator option only displays shortcut text and does not install a binding, so making Ctrl+S work requires an explicit binding of <Control-s> to the handler. Separately, mnemonic underlines come from the underline option, which names the character index to underline on the menu label. Applying those two settings fixes the reported shortcut and underline problems.

Exam trap

The trap here is assuming that specifying an accelerator automatically creates the keyboard shortcut, when in Tkinter it only renders the label text and a real binding is still required.

174
MCQhard

When implementing a timeout in 'requests.get()', what is the consequence of setting it as a single float (e.g., timeout=5)?

A.It only limits the read phase
B.It causes an error because a tuple is expected
C.It only limits the connection phase
D.It limits both the connection and read time to 5 seconds
AnswerD

Passing a single float sets both the connect and read timeouts to that value, so requests.get() aborts if the TCP connection is not established within 5 seconds or if no bytes arrive during any 5-second read window.

Why this answer

Providing a single value sets both the connect and read timeouts to that value.

175
MCQmedium

When working with raw sockets, what does the 'socket.SOCK_STREAM' constant represent?

A.UDP datagram sockets
B.Raw network sockets
C.TCP connection-oriented sockets
D.Unix domain sockets only
AnswerC

SOCK_STREAM selects a connection-oriented, reliable byte-stream transport, which on IP networks maps to TCP. It satisfies the stem's requirement by guaranteeing ordered, error-checked delivery, unlike SOCK_DGRAM, which provides connectionless UDP datagrams with no delivery guarantee.

Why this answer

socket.SOCK_STREAM designates a reliable, connection-oriented byte stream, which in practice maps to TCP (or a Unix-domain stream socket). The Python socket module passes this constant to socket() to select the transport semantics, so SOCK_STREAM sockets guarantee ordered, error-checked delivery via the TCP three-way handshake. This is why HTTP, SMTP, and SSH clients built on Python sockets use SOCK_STREAM.

Exam trap

PCPP1 often tests the confusion between socket type constants (SOCK_STREAM vs SOCK_DGRAM vs SOCK_RAW) and address family constants (AF_INET vs AF_UNIX), tricking candidates into thinking SOCK_STREAM implies a specific family or protocol.

How to eliminate wrong answers

Option A is wrong because UDP datagram sockets are represented by socket.SOCK_DGRAM, which is connectionless and message-oriented with no delivery guarantees. Option B is wrong because raw sockets are selected with socket.SOCK_RAW, which bypasses the transport layer and requires elevated privileges to craft packets directly. Option D is wrong because Unix domain sockets are chosen via the address family (AF_UNIX), not the socket type; SOCK_STREAM can be used with AF_UNIX, AF_INET, or AF_INET6, so it is not limited to Unix domain sockets.

176
MCQmedium

You are creating a dialog window in a Tkinter application that must block interaction with the main window until the user closes it, and must return a value to the caller. Which approach correctly implements this behavior?

A.Use the messagebox.askyesno() function, since it returns a value and is always modal.
B.Set the Toplevel's transient() option to True and call update() in a loop until the user closes it.
C.Create a Toplevel, call grab_set() on it, use wait_window() to wait until it is destroyed, then read the stored result.
D.Create a Toplevel, call its mainloop(), and read a global variable after it returns.
AnswerC

A Toplevel with grab_set() becomes modal, routing input events to it and preventing interaction with other windows. wait_window() then blocks the calling code until the dialog is destroyed, without starting a competing mainloop. Storing the result on the dialog instance before destroying it lets the caller read the value afterward. This is the standard, reliable pattern for modal dialogs in Tkinter.

Why this answer

A modal dialog must prevent input to other application windows and block the caller until dismissed. Creating a Toplevel, calling grab_set() to capture input, and then calling wait_window() achieves both: the grab routes events to the dialog, and wait_window() suspends the caller until the dialog is destroyed. Storing the result on the dialog instance before destruction lets the caller retrieve it after wait_window() returns.

Exam trap

The trap here is assuming that transient() alone creates modality or that calling mainloop() on a Toplevel is the proper way to wait for a dialog.

177
MCQeasy

A `Temperature` class stores a numeric `celsius` attribute. Callers keep assigning `temp.celsius = -500`, which is physically impossible. You want any assignment below absolute zero to raise `ValueError` while keeping normal attribute access unchanged. Which construct should you implement?

A.A `property` named `celsius` whose setter validates the incoming value before storing it in a private attribute.
B.Implement `__getattribute__` to compute `celsius` on demand and reject invalid reads with `ValueError`.
C.Define `__slots__ = ('celsius',)` so that Python enforces type and range constraints on the slot automatically.
D.Override `__setattr__` on the class to accept a value only when the attribute name is `celsius` and the value is valid.
AnswerA

A `property` intercepts attribute access through descriptor protocol methods, so the setter can validate before writing to an internal field such as `_celsius`. Reads remain transparent because the getter simply returns the stored value. This keeps the public name `celsius` while enforcing the constraint at assignment time, which is exactly the requested behavior.

Why this answer

A `property` is the idiomatic way to validate a single attribute: its setter runs on every assignment and can raise `ValueError` before the value is stored, while the getter preserves ordinary read syntax. Broader hooks like `__setattr__` or `__getattribute__` affect all attributes and are harder to reason about. Slots control structure, not values, so they cannot enforce the physical limit.

Exam trap

The trap here is reaching for `__setattr__` when the validation applies to only one attribute that a `property` can handle cleanly.

178
MCQhard

You are implementing a class `Matrix` that supports the `+` operator for matrix addition. You want `m1 + m2` to return a new `Matrix`, and you also want `sum([m1, m2, m3])` to work correctly. You define `__add__` to return a new `Matrix`. However, `sum([m1, m2, m3])` raises a `TypeError`. What is the most likely reason?

A.`sum()` calls `__add__` on the first element, but `Matrix.__add__` expects another `Matrix`, and `0` is not a `Matrix`.
B.`sum()` starts with `0` as the initial value, and `0 + m1` fails because `int.__add__` returns `NotImplemented` and `Matrix` lacks `__radd__`.
C.`sum()` requires the `__iadd__` method for in-place addition.
D.`sum()` requires all elements to be of the same type, and `0` is an `int`.
AnswerB

`sum()` begins with `0` and adds each element. The first operation is `0 + m1`, which calls `int.__add__(0, m1)` and returns `NotImplemented` because `int` cannot add a `Matrix`. Python then tries `Matrix.__radd__(m1, 0)`. If `__radd__` is not defined, a `TypeError` is raised. Implementing `__radd__` to handle the initial `0` (or any non-Matrix) fixes the issue.

Why this answer

`sum()` starts with `0` and adds each item. The first addition is `0 + m1`, which fails because `int.__add__` returns `NotImplemented` and `Matrix` does not define `__radd__`. To support `sum()`, you must implement `__radd__` to handle the initial `0` and any other non-Matrix left operand.

This makes the class compatible with the built-in `sum()` function.

Exam trap

The trap here is forgetting that `sum()` begins with `0`, so the first operation involves an `int` on the left, requiring a reflected addition method.

179
MCQeasy

Which standard Python library module is used for lower-level networking and creating server/client sockets?

A.http.server
B.requests
C.networking
D.socket
AnswerD

The socket module exposes the BSD socket interface directly, providing socket(), bind(), listen() and accept() for building servers and clients. It is the standard library's low-level networking foundation, satisfying the stem's requirement for lower-level socket creation rather than higher-level protocols.

Why this answer

The socket module is Python's standard library interface to the BSD sockets API, providing low-level networking primitives for creating TCP/UDP clients and servers. It exposes functions like socket(), bind(), listen(), accept(), connect(), send(), and recv(), making it the correct answer for lower-level networking. Higher-level modules like http.server and third-party libraries like requests are built on top of it.

Exam trap

PCPP1 often tests the distinction between standard library and third-party modules — candidates must recognize that requests is not part of the standard library and that 'networking' is not a real module, leaving socket as the only valid low-level option.

How to eliminate wrong answers

Option A is wrong because http.server is a high-level module for building simple HTTP servers; it abstracts away socket-level details and is not used for general lower-level networking. Option B is wrong because requests is a third-party HTTP client library (not part of the standard library) that operates at the HTTP protocol level, not the socket level. Option C is wrong because there is no standard library module named 'networking' in Python — this is a fabricated distractor.

180
Multi-Selecthard

Which THREE of the following are potential pitfalls of the Singleton pattern in Python?

Select 3 answers
A.They cannot be used with inheritance.
B.They introduce global state.
C.They cause difficulties in dependency injection.
D.They make unit testing more difficult.
E.They are always thread-safe.
AnswersB, C, D

A Singleton holds its instance in a shared, globally reachable location, so every consumer reads and writes the same state. This introduces global state, creating hidden coupling and making tests order-dependent and hard to isolate.

Why this answer

Option B is correct because a Singleton stores its single instance in a class-level or module-level location, effectively creating global mutable state that any part of the program can read or modify, which increases coupling and makes behavior harder to reason about. Option C is correct because Singleton clients typically call a hard-coded accessor such as getInstance() or reference a module-level instance directly, so you cannot easily substitute an alternative implementation through constructor injection or a DI container. Option D is correct because that same hard-coded access and shared state persist across tests, so tests can leak state into one another and cannot easily isolate the class under test with a mock or fake.

Option A is wrong because Singletons can participate in inheritance (subclasses can inherit or override the instance accessor), even if doing so is awkward. Option E is wrong because a naive Singleton implementation is not automatically thread-safe; without a lock or other synchronization, two threads can race and create multiple instances.

181
MCQmedium

A development team is refactoring a legacy Python module. They want to enforce a consistent import ordering convention across the codebase. According to PEP 8, which grouping and ordering of imports is considered best practice?

A.Standard library imports first, then third-party imports, then local application imports, with each group separated by a blank line.
B.Third-party imports first, followed by standard library imports, to highlight external dependencies.
C.Local application imports first, then standard library and third-party imports mixed together alphabetically.
D.All imports in a single block, sorted alphabetically by module name, regardless of origin.
AnswerA

PEP 8 specifies that imports should be grouped in the order: standard library, related third-party, and local application imports. Each group should be separated by a blank line. This ordering improves readability by clearly distinguishing built-in modules from external dependencies and project-specific modules, making it easier to manage and review dependencies.

Why this answer

PEP 8 recommends grouping imports into three distinct categories: standard library, third-party, and local application. Each group should be separated by a blank line. This ordering is not just stylistic; it helps developers quickly understand a module's dependencies and ensures that imports are logically organized.

Alphabetical sorting within each group is also encouraged but not mandatory.

Exam trap

The trap here is assuming that alphabetical order across all imports is sufficient, overlooking the required grouping by origin.

182
Multi-Selectmedium

A developer is designing a `Shape` base class and wants subclasses to be forced to implement an `area()` method. Which two approaches are valid in Python for enforcing that subclasses provide `area()`? (Choose two.)

Select 2 answers
A.Define `area` in the base class with a body that raises `NotImplementedError`, so subclasses fail at call time if they forget to override.
B.Inherit from `abc.ABC` and decorate `area` with `@abstractmethod`, so instantiation fails until the method is overridden.
C.Assign `area = None` in the base class body so calling `area()` raises TypeError automatically.
D.Decorate `area` with `@staticmethod` in the base class so subclasses must redefine it to avoid a TypeError.
E.Use `__slots__ = ('area',)` in the base class to declare `area` as a required slot that subclasses must fill.
AnswersA, B

Raising `NotImplementedError` in the base method is a widely used convention that surfaces missing overrides at runtime when the method is called. It does not prevent instantiation, but it does enforce that subclasses provide their own implementation to avoid the exception. This is valid though less strict than ABC-based enforcement.

Why this answer

Python enforces method implementation either through the `abc` module's `@abstractmethod` mechanism, which blocks instantiation until overrides exist, or through a base method that raises `NotImplementedError` at call time. The first is stricter and catches errors earlier; the second is a simpler convention that still signals missing overrides clearly.

Exam trap

The trap here is treating `@staticmethod` or `__slots__` as enforcement mechanisms, when neither imposes any obligation on subclasses to override a method.

183
MCQeasy

A team is reviewing code and notices that a function uses a mutable default argument: def append_to(element, target=[]):. Which change best adheres to Python best practices and avoids unexpected behavior?

A.def append_to(element, target=[]): target.append(element); return target
B.def append_to(element, target=None): if target is None: target = []
C.def append_to(element, target=list()): target.append(element); return target
D.def append_to(element, target=()): target.append(element); return target
AnswerB

Using None as the default and creating a new list inside the function prevents the mutable default from being shared across calls. This is the recommended pattern in Python to avoid the well-known pitfall of mutable default arguments, ensuring each call gets a fresh list when no target is provided.

Why this answer

Mutable default arguments are evaluated once at function definition, so using a list as a default causes state to persist across calls. The best practice is to use None as the default and create a new list inside the function. This ensures each call without an explicit target gets a fresh list, preventing unintended side effects.

Exam trap

The trap here is thinking that replacing [] with list() or () avoids the mutable default problem, but only using None as a sentinel and creating the list inside the function truly fixes it.

184
Multi-Selecthard

Which THREE of the following widgets are part of the 'ttk' (Themed Tkinter) module?

Select 3 answers
A.ttk.Entry
B.ttk.Button
C.ttk.Label
D.ttk.Window
E.ttk.Canvas
AnswersA, B, C

ttk.Entry is the themed counterpart of tkinter.Entry, wrapping the native Tk themed widget set. Its presence in the ttk module satisfies the stem's criterion of identifying widgets belonging to Themed Tkinter, distinguishing it from the classic tkinter.Entry class.

Why this answer

Options A, B, and C are correct because ttk.Entry, ttk.Button, and ttk.Label are all genuine themed widgets provided by the tkinter.ttk module, replacing their classic Tkinter counterparts (tkinter.Entry, tkinter.Button, tkinter.Label) with native-looking, theme-aware versions. ttk.Entry provides a themed single-line text input, ttk.Button provides a themed push button, and ttk.Label provides a themed non-editable text or image display. Option D is incorrect because there is no ttk.Window widget; top-level windows are created with tkinter.Tk or tkinter.Toplevel, and ttk offers no window class. Option E is incorrect because ttk.Canvas does not exist; the canvas widget is only available as tkinter.Canvas in the classic Tk widget set, not in the themed ttk module.

185
MCQmedium

How do you implement the 'Strategy' pattern in Python?

A.By using a large switch-case statement.
B.By creating a metaclass for all strategies.
C.By passing strategy instances into the context constructor.
D.By using inheritance for every strategy.
AnswerC

Constructor injection lets the context hold a reference to an abstract strategy object, so algorithms are selected at runtime without subclassing the context. This satisfies the pattern's requirement of interchangeable behaviour, since swapping the passed instance changes the algorithm while the context's interface stays fixed.

Why this answer

By injecting different strategy objects into a context class, which then delegates operations to the injected object.

186
MCQeasy

Which module must be imported to utilize Tkinter in a Python script?

A.import tkinter
B.import gui
C.from python import gui
D.import tk
AnswerA

Importing `tkinter` binds the standard-library GUI package directly, satisfying the stem's requirement to utilise Tkinter. Unlike third-party alternatives such as PyQt, it ships with CPython, so no separate installation is needed. The module exposes widgets, geometry managers and the main event loop, letting the script construct and run a window immediately.

Why this answer

Tkinter is Python's standard GUI library, and it is imported with the statement 'import tkinter' (lowercase). This is the correct module name in Python 3; in Python 2 it was 'Tkinter' with a capital T, but Python 3 standardized it to lowercase.

Exam trap

The trap is the Python 2 vs. Python 3 naming difference — candidates who learned on Python 2 may pick 'Tkinter' (capital T), but the exam expects the Python 3 lowercase 'tkinter'.

How to eliminate wrong answers

Option B is wrong because there is no standard module named 'gui' in Python — it is a fabricated name. Option C is wrong because 'from python import gui' is syntactically and semantically invalid; 'python' is not a module, and 'gui' is not a submodule. Option D is wrong because 'tk' is not the module name — while there is a 'tkinter.ttk' submodule for themed widgets, the top-level module is 'tkinter', not 'tk'.

187
MCQmedium

When designing a class hierarchy, what is the best way to prevent a method from being overridden by subclasses?

A.Defining it as a private method.
B.Defining it as a static method.
C.Using the @final decorator from typing.
D.Using the 'final' keyword.
AnswerC

The @final decorator from typing marks the method so type checkers flag any subclass override, satisfying the requirement to prevent overriding. At runtime it does not enforce, but it is the documented, idiomatic mechanism for declaring a method non-overridable in a hierarchy.

Why this answer

The @final decorator from the typing module (PEP 591) is the standard, type-checker-enforced way to mark a method as non-overridable in Python. When applied to a method, static type checkers like mypy or Pyright will flag any subclass that attempts to override it, and applying @final to a class prevents subclassing entirely. Python itself does not enforce this at runtime, but the decorator is the idiomatic, documented mechanism for expressing the intent.

Exam trap

PCPP1 often tests the misconception that Python has a 'final' keyword like Java or C#, or that private (double-underscore) methods are truly non-overridable — candidates must recognize that @final from typing is the correct, PEP 591-sanctioned mechanism.

How to eliminate wrong answers

Option A is wrong because a private method (name-mangled with a leading double underscore) is only hidden from subclasses via name mangling — a subclass can still define a method with the same name and effectively override behavior, and Python does not prevent this. Option B is wrong because static methods are simply methods that don't receive self or cls; they can be overridden by subclasses just like any other method, so they provide no protection. Option D is wrong because 'final' is not a Python keyword — Python has no built-in final keyword; finality is expressed via the typing.final decorator or the @final annotation.

188
MCQeasy

You have a Button widget and want to trigger a function named 'process_data' when the user clicks it. Which is the standard way to associate the function with the button?

A.button = Button(root, event=process_data)
B.button.bind('<Button-1>', process_data)
C.button = Button(root, command=process_data)
D.button.set_action(process_data)
AnswerC

Passing the function object directly to the `command` parameter binds `process_data` as the button's callback, so Tkinter invokes it on each click without arguments. This satisfies the stem's requirement for the standard association method, unlike `bind()`, which links events rather than the widget's built-in command hook.

Why this answer

The 'command' parameter is the standard way to bind a callback function to a button click event.

189
MCQeasy

A developer wants to ensure that a method `area` in a base class `Shape` must be overridden by any concrete subclass. The developer writes `class Shape(ABC):` and `@abstractmethod def area(self): ...`. A colleague then creates `class Circle(Shape):` without implementing `area` and tries to instantiate `Circle()`. What happens?

A.`Circle()` succeeds and `area()` returns `None` because the base method body is `...`.
B.A `TypeError` is raised at instantiation time because `Circle` still has abstract methods.
C.`Circle()` succeeds, and calling `area()` later raises `NotImplementedError`.
D.A `SyntaxError` is raised when the `Circle` class definition is parsed.
AnswerB

`ABCMeta` tracks unimplemented abstract methods. When `Circle` does not override `area`, its `__abstractmethods__` set still contains `'area'`, and calling `Circle()` triggers `TypeError: Can't instantiate abstract class Circle with abstract method area`. This is exactly the enforcement `@abstractmethod` provides.

Why this answer

The `ABCMeta` metaclass maintains a set of abstract method names on each class. A subclass that does not override all of them keeps a non-empty set, and instantiation raises `TypeError`. The `...` body is irrelevant because the abstract method is never invoked; enforcement happens before the object exists.

Exam trap

The trap here is assuming the abstract method body runs and raises `NotImplementedError`, when actually instantiation is blocked by the metaclass.

190
Multi-Selecthard

Which THREE of the following are valid methods of the xml.etree.ElementTree.Element class?

Select 3 answers
A.find()
B.write()
C.append()
D.set()
E.to_string()
AnswersA, C, D

find() traverses direct child elements matching a tag or path, returning the first match or None. It is a genuine Element method, satisfying the question's requirement for valid Element class methods alongside append() and set().

Why this answer

The xml.etree.ElementTree.Element class provides find(), append(), and set() as valid instance methods. find(match) searches the element's direct children for the first subelement matching the tag or path and returns it (or None), which is a core Element API method. append(subelement) adds a child Element to the end of the element's list of children, and set(key, value) sets an attribute on the element, both being standard Element methods. write() is not an Element method; it belongs to the ElementTree class (ElementTree.write(file, encoding, xml_declaration, ...)), which serializes the whole tree to a file. to_string() is also not an Element method; serialization to a string is done via xml.etree.ElementTree.tostring(element) (no underscore), so option E is invalid.

191
MCQeasy

You are placing several widgets in a window using the grid() geometry manager and want a widget to span multiple columns in the same row. Which grid() option accomplishes this?

A.ipadx
B.rowspan
C.columnspan
D.sticky
AnswerC

columnspan tells grid() that the widget should occupy the specified number of adjacent columns starting at its column index. Setting columnspan=3, for example, makes the widget stretch across three columns in its row. This is exactly the option needed to have a widget span multiple columns, and it works together with sticky to control how the widget fills the spanned area.

Why this answer

In grid(), the columnspan option specifies how many columns a widget should occupy, starting from its column index. This is the mechanism for horizontal spanning within a row. rowspan handles vertical spanning, sticky controls alignment and stretching inside the cell, and ipadx adds internal padding. Combining columnspan with sticky lets a widget both cover several columns and fill the resulting space as desired.

Exam trap

The trap here is confusing columnspan with sticky or ipadx, which change alignment or padding but never alter how many grid cells the widget occupies.

192
MCQeasy

You are writing a script that downloads a large file from a REST endpoint using `requests.get(url, stream=True)`. You want to write the content to disk in chunks rather than loading it all into memory. Which approach correctly implements chunked reading?

A.file.write(response.raw.read())
B.for chunk in response.iter_content(chunk_size=8192): file.write(chunk)
C.for chunk in response.iter_lines(): file.write(chunk)
D.file.write(response.content)
AnswerB

iter_content() yields the response body in chunks of the specified size, allowing you to write each chunk to disk without holding the entire file in memory. This is the documented pattern for streaming downloads with requests and works with stream=True to avoid buffering the full response.

Why this answer

Streaming a large download requires reading the body incrementally. The iter_content() method yields chunks of a specified size and is the standard way to write streaming responses to disk without buffering the whole payload. Using response.content or response.raw.read() without a size loads everything into memory, while iter_lines() is intended for line-delimited text streams.

Exam trap

The trap here is confusing iter_lines(), which splits on newlines, with iter_content(), which yields fixed-size byte chunks suitable for binary files.

193
MCQmedium

You are designing a class `Connection` that must ensure only one instance exists and that the same instance is returned whenever `Connection()` is called. You implement this using `__new__` to control instance creation, and you also define `__init__`. During testing, you notice that `__init__` runs every time `Connection()` is called, even though `__new__` returns the existing singleton instance. What is the most appropriate way to prevent `__init__` from reinitializing the singleton on subsequent calls?

A.Delete the `__init__` method so only `__new__` runs.
B.Use a metaclass to override `__call__` and cache the instance.
C.Override `__new__` to return `None` when an instance already exists.
D.Use a class-level flag to track initialization and guard the `__init__` logic.
AnswerD

Python always calls `__init__` on the object returned by `__new__` if it is an instance of the class. A class-level boolean flag set after the first initialization lets `__init__` skip reinitialization on later calls, preserving the singleton's state. This is the standard, explicit way to prevent repeated initialization while still returning the same object.

Why this answer

When `__new__` returns an existing instance, Python still calls `__init__` on it. To avoid reinitialization, the class must explicitly track whether initialization has already occurred. A class-level flag checked at the start of `__init__` is the simplest, most readable solution.

It preserves the singleton's state and avoids side effects from repeated setup, which is critical for resources like connections.

Exam trap

The trap here is assuming that returning an existing instance from `__new__` prevents `__init__` from running again.

194
MCQhard

A developer defines `class Config:` with `__slots__ = ('host', 'port')`. Later, they want to add a new attribute `timeout` to an existing instance without modifying the class. They write `cfg.timeout = 30` and receive an `AttributeError`. Which change would allow per-instance `timeout` assignment while keeping `__slots__` for `host` and `port`?

A.Add `'__dict__'` to `__slots__`.
B.Add a `__getattr__` method that returns `30` for unknown names.
C.Subclass `Config` and add `__slots__ = ()` in the subclass.
D.Change `__slots__` to a dictionary mapping names to default values.
AnswerA

Including `'__dict__'` in `__slots__` reserves a per-instance dictionary in addition to the slot descriptors. Instances still get fast slot storage for `host` and `port`, but also accept arbitrary new attributes like `timeout`. This is the documented way to opt back into dynamic attributes while retaining slots for the declared names.

Why this answer

Slot descriptors are the only writable attributes unless the class also provides a `__dict__`. Declaring `'__dict__'` inside `__slots__` creates that dictionary, so new names like `timeout` can be stored per instance while `host` and `port` remain fast slots. The other options either do not affect assignment or misuse the `__slots__` contract.

Exam trap

The trap here is thinking `__getattr__` or a subclass trick enables assignment, when only adding `__dict__` to `__slots__` restores dynamic attributes.

195
Multi-Selectmedium

Which TWO of the following are potential pitfalls when using multithreading for network operations in Python?

Select 2 answers
A.Race conditions when accessing shared state
B.The GIL prevents true parallelism for CPU-bound tasks
C.Threads always execute slower than single-threaded code
D.Threads consume more memory than processes
E.Socket objects are automatically thread-safe
AnswersA, B

Shared mutable state accessed by multiple threads without locking permits interleaved reads and writes, producing race conditions and corrupted results. This satisfies the stem's pitfall criterion because Python's GIL serialises bytecode execution but does not make compound operations atomic, so concurrent network handlers updating shared buffers remain unsafe.

Why this answer

Option A is correct because when multiple threads access and modify shared state (such as a shared socket buffer, connection pool, or counter) without proper synchronization primitives like locks, race conditions can occur, leading to corrupted data or unpredictable behavior. Option B is correct because Python's Global Interpreter Lock (GIL) allows only one thread to execute Python bytecode at a time, so multithreading does not achieve true parallelism for CPU-bound tasks—though it can still help with I/O-bound network operations where threads block on socket calls. Option C is incorrect because threads do not always execute slower than single-threaded code; for I/O-bound network operations, multithreading often improves throughput by overlapping waiting periods.

Option D is incorrect because threads within a process share the same memory space and typically consume less memory overhead than separate processes, not more. Option E is incorrect because socket objects in Python are not automatically thread-safe; concurrent access to the same socket from multiple threads can cause data corruption or errors unless explicitly synchronized.

196
MCQhard

How should one handle the 'KeyboardInterrupt' exception if it must be caught for cleanup purposes?

A.Catch it, clean up resources, and then use 'raise'.
B.Prevent it by setting a signal handler for SIGINT.
C.Use a bare 'except:' clause.
D.Catch it and ignore it to keep the app running.
AnswerA

KeyboardInterrupt signals user-requested termination, so swallowing it would leave the interpreter in an inconsistent state. Catching it solely to release resources, then re-raising with bare raise, preserves the original traceback and lets the interrupt propagate as intended.

Why this answer

You should catch it, perform the cleanup, and then re-raise it so the application still shuts down gracefully.

197
Multi-Selecthard

You are designing a Python REST API client that must handle HTTP errors gracefully. The client uses the requests library. Which TWO of the following statements about error handling with requests are correct? (Choose two.)

Select 2 answers
A.The response.raise_for_status() method raises an HTTPError if the HTTP status code indicates a client error (4xx) or server error (5xx).
B.The requests.exceptions.ConnectionError is raised when the server returns a 500 Internal Server Error status code.
C.The requests.exceptions.Timeout exception is raised when the server returns a 408 Request Timeout status code.
D.The response.status_code attribute returns the HTTP status code as an integer, and you can compare it directly to constants like requests.codes.ok.
E.By default, requests automatically raises an exception for any HTTP status code other than 200 OK.
AnswersA, D

This statement is correct. The raise_for_status() method checks the status code and raises an HTTPError exception for 4xx and 5xx responses. It is a convenient way to ensure that only successful responses (2xx) proceed, and it provides access to the response object for further inspection.

Why this answer

The raise_for_status() method is the idiomatic way to trigger exceptions for HTTP error statuses, and status_code provides the numeric code for manual checks. The other statements confuse network-level exceptions with HTTP status codes, or incorrectly assume automatic error raising. Understanding these distinctions is crucial for robust API clients.

Exam trap

The trap here is conflating network exceptions (like ConnectionError or Timeout) with HTTP status code errors, and assuming requests automatically raises exceptions for all non-200 responses.

198
MCQmedium

How do you correctly call a method from a sibling class in a diamond inheritance structure using super()?

A.Call the grandparent class directly.
B.Use super() in each class to delegate to the next class in the MRO.
C.Use the __bases__ attribute to iterate through parents.
D.Explicitly call the sibling class method by name.
AnswerB

Using `super()` in each class delegates along Python's C3 linearisation, so every sibling in the diamond is invoked exactly once in method resolution order. This satisfies the stem's requirement to reach a sibling class without duplicating the shared base, which direct base-class calls would trigger.

Why this answer

super() follows the Method Resolution Order (MRO), which correctly handles diamond inheritance by delegating calls to the next class in the chain, not just the parent.

199
MCQmedium

You are using the sqlite3 module to manage a database. You need to ensure that database changes are permanently saved even if your script terminates unexpectedly. Which method should you call after an INSERT operation?

A.connection.save()
B.cursor.flush()
C.connection.close()
D.connection.commit()
AnswerD

Calling connection.commit() writes the pending transaction to disk, making the INSERT durable. SQLite wraps changes in an implicit transaction, so without commit they are rolled back when the script terminates unexpectedly. This directly satisfies the stem's requirement that changes be permanently saved despite abnormal termination.

Why this answer

The commit() method on a connection object is required to save changes permanently in sqlite3.

200
MCQmedium

You are developing a Python application that uses a third-party library. You need to ensure that your code handles exceptions raised by that library in a way that is both robust and follows best practices. The library raises a custom exception named LibraryError, which is a subclass of Exception. Your function calls a method that may raise LibraryError. Which of the following is the best approach to handle this exception?

A.try: result = library.method() except LibraryError: print("An error occurred")
B.try: result = library.method() except Exception: pass
C.try: result = library.method() except LibraryError as e: logger.error("Library method failed: %s", e) raise
D.try: result = library.method() except BaseException as e: logger.error("Error: %s", e)
AnswerC

This approach catches the specific exception, logs it with a meaningful message, and re-raises it to allow the caller to handle it appropriately. It follows best practices by not swallowing the exception, preserving the traceback, and providing context. It also avoids catching unrelated exceptions, making the error handling precise and maintainable.

Why this answer

The best practice is to catch the specific exception, log it with context, and re-raise it to allow higher-level handlers to decide how to proceed. This preserves the traceback and ensures that the error is not silently ignored. Catching only LibraryError avoids masking unrelated issues, and using a logger instead of print provides proper production-grade logging.

Exam trap

The trap here is thinking that catching a broad exception like Exception or BaseException is safer, when in fact it can hide critical errors and make debugging harder.

201
MCQmedium

You are building a Tkinter application with a menu bar. You want to add a 'File' menu with an 'Exit' item that terminates the application when selected. Which command should you associate with the 'Exit' menu item to properly close the application?

A.sys.exit
B.root.quit
C.root.end
D.root.destroy
AnswerD

Calling root.destroy() terminates the Tkinter application by destroying the main window and ending the mainloop. It is the standard way to exit a Tkinter app cleanly. Associating this method with the menu item will close the application when the user selects 'Exit'.

Why this answer

To properly close a Tkinter application from a menu item, you should call the destroy method on the root window. This destroys all widgets and exits the mainloop. The quit method only stops the mainloop, and sys.exit may not clean up GUI resources.

There is no end method.

Exam trap

The trap here is thinking that quit or sys.exit will fully close the application, when destroy is the correct method for a clean exit.

202
Multi-Selecteasy

Which TWO of the following are valid ways to create a connection in the sqlite3 module?

Select 2 answers
A.sqlite3.connect(':memory:')
B.sqlite3.Connection('my_db.sqlite')
C.sqlite3.connect('my_db.sqlite')
D.sqlite3.new_db('my_db.sqlite')
E.sqlite3.open('my_db.sqlite')
AnswersA, C

Passing `':memory:'` to `sqlite3.connect()` opens a private, temporary database held entirely in RAM, satisfying the scenario's requirement for an in-memory connection. No file is created on disk, and the database vanishes when the connection closes. This is a documented, valid connection string accepted by the sqlite3 module.

Why this answer

Option A, sqlite3.connect(':memory:'), is correct because sqlite3.connect() is the module's factory function for creating a Connection object, and passing the special filename ':memory:' opens a temporary in-memory database. Option C, sqlite3.connect('my_db.sqlite'), is also correct because the same sqlite3.connect() function accepts a filesystem path and returns a Connection to that database file, creating it if it does not exist. The other options are invalid: sqlite3.Connection is the class of connection objects and is not normally instantiated directly with a filename, while sqlite3.new_db and sqlite3.open are not functions provided by the sqlite3 module.

203
Multi-Selecteasy

Which THREE of the following are standard ways to handle API authentication?

Select 3 answers
A.OAuth 2.0
B.API Keys
C.Public IP Whitelisting
D.Basic Authentication
E.Hardcoding passwords in code
AnswersA, B, D

OAuth 2.0 is a delegated authorisation framework where clients obtain access tokens from an authorisation server, avoiding credential sharing. It satisfies the scenario's requirement for a standard API authentication method, unlike ad-hoc schemes, and is widely adopted for third-party access.

Why this answer

OAuth 2.0 (A) is a standard authorization framework that issues access tokens via grant flows (authorization code, client credentials, etc.), allowing scoped, revocable API access without sharing credentials. API Keys (B) are a widely used standard mechanism where a unique key identifies and authenticates the calling application, typically passed in a header or query parameter. Basic Authentication (D) is an HTTP-standard scheme (RFC 7617) that sends a Base64-encoded username:password in the Authorization header, commonly used for simple API authentication over TLS.

Public IP Whitelisting (C) is a network access control, not an authentication method, since it does not verify caller identity. Hardcoding passwords in code (E) is an insecure anti-pattern that exposes credentials and is not a standard authentication approach.

204
MCQhard

When documenting a complex function, which approach is most compliant with Google Style Python Docstrings regarding parameter types?

A.Use the 'Args:' section followed by the parameter name, type, and description.
B.Embed the types directly in the function name.
C.Include type hints in the docstring but omit them from the function signature.
D.Avoid documenting types to prevent redundancy with type hints.
AnswerA

Google Style mandates an `Args:` section where each parameter appears as `name (type): description`, satisfying the stem's requirement to document parameter types explicitly. This structured format lets tools such as Sphinx napoleon parse types reliably, unlike free-form prose or reStructuredText `:param:` fields, which Google Style does not use.

Why this answer

Google Style Python Docstrings require an 'Args:' section where each parameter is listed with its name, type, and description in the format 'name (type): description'. This makes the function's interface self-documenting and consistent with tools like Sphinx Napoleon that parse Google-style docstrings.

Exam trap

The trap is assuming type hints make docstring types redundant — candidates may pick option D, not realizing Google Style explicitly requires types in the Args section for documentation completeness and tooling compatibility.

How to eliminate wrong answers

Option B is wrong because embedding types in the function name is not a documentation practice at all — it would produce unreadable, non-PEP 8 compliant identifiers. Option C is wrong because Google Style encourages documenting types in the docstring while still using type hints in the signature — omitting them from the signature defeats the purpose of static analysis. Option D is wrong because Google Style explicitly includes types in the Args section; type hints and docstring types serve different audiences (static analyzers vs. human readers and documentation generators).

205
Multi-Selectmedium

Which TWO of the following are correct regarding the 'with' statement in Python?

Select 2 answers
A.It works by implicit __init__ calling.
B.It only works with file objects.
C.It can be used with any object.
D.It requires the class to define __enter__ and __exit__.
E.It guarantees that __exit__ is called even if an exception occurs.
AnswersD, E

The context manager protocol requires the class to implement __enter__, invoked on entry to the with block, and __exit__, invoked on exit. Without both methods defined, Python raises AttributeError, so this is a genuine requirement of the with statement's protocol.

Why this answer

Option D is correct because the context manager protocol requires the object used in a 'with' statement to implement the special methods __enter__() (which runs on entry and may return a value bound via 'as') and __exit__() (which runs on exit and receives exception type, value, and traceback). Option E is correct because the 'with' statement is semantically equivalent to a try/finally block, so __exit__() is invoked whether the block completes normally or raises an exception, ensuring cleanup such as closing files or releasing locks. Option A is wrong because 'with' does not rely on __init__; initialization happens when the object is constructed, not when the context is entered.

Option B is wrong because 'with' is not limited to file objects; any object implementing the context manager protocol works, including locks, sockets, and database connections. Option C is wrong as stated because not every object supports the protocol — only those defining __enter__ and __exit__ can be used directly in a 'with' statement.

206
MCQhard

You are investigating a network bottleneck in your Python application using `requests`. If you aren't using a `Session` object, what performance-related behavior should you expect?

A.Each request will perform a full TCP handshake
B.The application will use more memory
C.Connection pooling will be enabled by default
D.The server will block your IP immediately
AnswerA

Without a Session, each requests call opens a fresh connection, repeating the full TCP handshake and TLS negotiation per request. This satisfies the bottleneck scenario: connection setup overhead accumulates across calls, whereas a Session pools and reuses connections via keep-alive.

Why this answer

Without a Session, each request creates a new TCP connection, incurring the cost of a three-way handshake every time.

207
MCQmedium

In the context of the Factory pattern, what does a concrete factory implement?

A.The registration logic for all factories.
B.The creation interface for specific product variants.
C.The logic for the singleton pattern.
D.The product logic.
AnswerB

A concrete factory implements the abstract creation interface declared by the factory, returning concrete product instances for a specific variant. This lets client code request products through the shared interface while remaining decoupled from the concrete classes.

Why this answer

A concrete factory implements the interface defined by the abstract factory to produce specific products.

208
MCQeasy

You are writing a Python script that needs to send a GET request to a REST API and parse the JSON response. The API requires an API key passed as a query parameter. Which code snippet correctly performs this request using the requests library?

A.requests.get('https://api.example.com/data', data={'api_key': '12345'})
B.requests.get('https://api.example.com/data?api_key=12345')
C.requests.get('https://api.example.com/data', params={'api_key': '12345'})
D.requests.get('https://api.example.com/data', headers={'api_key': '12345'})
AnswerC

This uses the params argument to pass a dictionary of query parameters, which requests will URL-encode and append to the URL. It correctly sends the API key as a query parameter, as required by the scenario. The response can then be parsed with response.json(). This is the standard and correct way to include query parameters in a GET request.

Why this answer

The params argument in requests.get() is the correct way to pass query parameters. It automatically URL-encodes the dictionary and appends it to the URL. Using headers or data would not place the API key in the query string as required.

Manually constructing the URL is error-prone and less secure.

Exam trap

The trap here is confusing the data argument with params, or assuming that any argument that accepts a dictionary will work for query parameters.

209
MCQmedium

In the csv module, how do you specify that the CSV file uses a semicolon (;) as a delimiter?

A.csv.reader(f, char=';')
B.csv.reader(f, sep=';')
C.csv.reader(f, quotechar=';')
D.csv.reader(f, delimiter=';')
AnswerD

Passing delimiter=';' to csv.reader overrides the default comma, so the parser splits each row on semicolons instead. This directly satisfies the stem's requirement for a semicolon-separated file, since the delimiter argument defines the field separator character.

Why this answer

The delimiter parameter in the csv.reader or csv.writer function is used for this purpose.

210
MCQmedium

When implementing the Singleton pattern, what is the advantage of using a module-level instance over a class-based Singleton?

A.It is more secure.
B.It allows multiple instances if needed.
C.It is simpler and leverages Python's built-in module caching mechanism.
D.It supports lazy loading.
AnswerC

Python caches imported modules in sys.modules, so a module-level instance is created once at import and shared thereafter. This gives singleton behaviour with no metaclass, __new__ override or locking, satisfying the pattern with less code.

Why this answer

Python modules are naturally Singletons because they are initialized only once upon the first import.

211
MCQeasy

You are creating a Tkinter GUI with a Canvas widget to draw a simple chart. You need to draw a filled blue rectangle from (50, 50) to (150, 100). Which Canvas method call achieves this?

A.canvas.create_rectangle(50, 50, 150, 100, fill='blue')
B.canvas.create_polygon(50, 50, 150, 100, fill='blue')
C.canvas.create_oval(50, 50, 150, 100, fill='blue')
D.canvas.create_line(50, 50, 150, 100, fill='blue', width=50)
AnswerA

create_rectangle accepts the two corner coordinates and an optional fill colour, so this call draws a rectangle with a blue interior exactly between the specified points. The Canvas widget's coordinate system places (0,0) at the top-left, so the shape appears in the expected location, satisfying the requirement.

Why this answer

The Canvas widget offers dedicated factory methods for common shapes. create_rectangle takes two coordinate pairs that define the top-left and bottom-right corners and accepts a fill option for the interior colour. Using the correct method ensures the shape is actually a rectangle rather than a degenerate polygon, a thick line, or an ellipse.

Exam trap

The trap here is assuming that any shape method with the same coordinates will produce a rectangle, when create_polygon needs four points and create_oval produces an ellipse.

212
MCQeasy

What is the purpose of the __repr__ method?

A.To be called by print().
B.User-friendly output.
C.To store the object in memory.
D.Unambiguous representation for debugging.
AnswerD

The `__repr__` method returns an unambiguous string representation of an object, intended primarily for developers and debugging. Unlike `__str__`, which prioritises readability for end users, `__repr__` should ideally produce output that could recreate the object, satisfying the requirement for precise, diagnostic output.

Why this answer

It provides a formal, unambiguous string representation of an object, ideally suitable for re-creating the object.

213
Multi-Selectmedium

A developer is writing a Python module and wants to follow best practices for documenting functions. Which TWO of the following are recommended by PEP 257 for docstrings? (Choose two.)

Select 2 answers
A.The docstring should be enclosed in triple double quotes (""").
B.The docstring should be a single line that ends with a period.
C.The docstring should be separated from the function definition by a blank line.
D.The docstring should describe the function's purpose and its parameters.
E.The docstring should be written in all uppercase letters.
AnswersA, D

PEP 257 recommends using triple double quotes for docstrings. This is the standard convention, and it allows multi-line docstrings. Using triple single quotes is also valid, but triple double quotes are preferred for consistency and to avoid conflicts with apostrophes in the text.

Why this answer

PEP 257 recommends using triple double quotes for docstrings and that they should describe the function's purpose and parameters. It also advises that a one-line docstring should end with a period, but does not require all docstrings to be single-line. No blank line should precede the docstring, and there is no rule about uppercase.

Exam trap

The trap here is assuming that all docstrings must be single-line or that a blank line before the docstring is acceptable, when PEP 257 specifies no blank line before and allows multi-line docstrings.

214
MCQmedium

What is the primary benefit of using 'logging' over 'print' statements for application diagnostics?

A.It is faster for small scripts.
B.It prevents the application from crashing on errors.
C.It allows setting severity levels and routing logs to different handlers.
D.It automatically cleans up log files.
AnswerC

The logging module assigns severity levels and dispatches records to configurable handlers such as files, streams or syslog, unlike print's single hardcoded output. This routing and filtering capability is the diagnostic advantage the stem asks for.

Why this answer

The 'logging' module provides granular control over levels, destinations, and output formatting without changing the source code.

215
MCQhard

Why does the 'abc' module provide the 'ABCMeta' metaclass?

A.To allow private methods.
B.To improve method resolution speed.
C.To enforce abstract method implementation at instantiation.
D.To support multiple inheritance.
AnswerC

ABCMeta intercepts instantiation of classes using abstractmethod, raising TypeError when any abstract method remains unimplemented. This enforces the contract at object creation time, rather than merely documenting it, which is the enforcement the abc module exists to provide.

Why this answer

ABCMeta is the metaclass that implements the logic to prevent instantiation of classes with abstract methods.

216
MCQmedium

Which method in the xml.dom.minidom module is used to retrieve the value of a specific attribute of an element?

A.element.attr('attr_name')
B.element.getAttribute('attr_name')
C.element.getAttributeNode('attr_name').value
D.element.value('attr_name')
E.element['attr_name']
AnswerB

getAttribute() reads a named attribute's value directly from an Element node, returning a string or empty string if absent. It satisfies the stem's requirement to retrieve one specific attribute by name, unlike attributes or childNodes, which expose whole collections rather than a single value.

Why this answer

The getAttribute() method is used to retrieve the value of an attribute by its name.

217
MCQmedium

You want to execute multiple SQL statements at once in sqlite3. Which method should you use?

A.cursor.executescript()
B.connection.execute_all()
C.cursor.execute_script()
D.cursor.execute_many()
AnswerA

`executescript()` passes the entire SQL string to SQLite's `sqlite3_exec`, which parses and runs each semicolon-separated statement sequentially, satisfying the requirement to execute multiple statements in one call. Unlike `execute()`, which rejects trailing statements after the first, it commits pending transactions beforehand.

Why this answer

The executescript() method allows executing multiple SQL statements separated by semicolons.

218
MCQmedium

When using the 'socket' module, what is the effect of calling 'socket.settimeout(5.0)' on a socket object?

A.It sets the send buffer size to 5.0 bytes
B.It causes the operation to raise a socket.timeout after 5 seconds
C.It blocks the thread for exactly 5 seconds
D.It forces the socket to close after 5 seconds of inactivity
AnswerB

Setting a socket timeout places the descriptor in non-blocking mode with a deadline: blocking calls such as `recv()`, `send()` or `accept()` raise `socket.timeout` once 5 seconds elapse without completing. This satisfies the stem's requirement that the operation itself fails after the specified interval rather than waiting indefinitely.

Why this answer

The settimeout() method sets a timeout in seconds for subsequent socket operations. If the operation does not complete within the time, a socket.timeout exception is raised.

219
MCQmedium

You maintain a Tkinter inventory dashboard whose main window contains a large frame with a Treeview listing warehouse items. Operators complain that when they maximize the window, the Treeview stays at its original size and leaves a large empty gray area. The frame is already managed with grid() and the Treeview is placed inside that frame with pack(). Which single change most directly makes the Treeview grow with the frame when the window is resized?

A.Call tree.config(width=200, height=50) so the Treeview requests a larger size whenever the window is maximized.
B.Call tree.pack(fill='both', expand=True) and configure the frame's row and column weights with frame.grid_rowconfigure(0, weight=1) and frame.grid_columnconfigure(0, weight=1).
C.Replace pack() with place() and use relwidth=1, relheight=1 so the Treeview always occupies the whole frame.
D.Set the frame's propagate(False) method and assign explicit pixel dimensions to the Treeview's width and height attributes.
AnswerB

This is the standard Tkinter recipe for a Treeview that tracks its container: pack(fill='both', expand=True) lets the widget claim extra space inside its parent frame, while grid_rowconfigure and grid_columnconfigure with weight=1 make the frame's internal cell distribute surplus space to the Treeview's row and column. Without the weight settings, the frame keeps the child at its requested size even when the frame itself grows.

Why this answer

A Treeview that must follow its parent needs two cooperating mechanisms: the geometry manager inside the frame must allow expansion, and the frame must be told to give surplus space to the cell containing the Treeview. Combining pack(fill='both', expand=True) with weighted grid rows and columns satisfies both conditions, which is why this is the canonical Tkinter pattern for resizable data tables.

Exam trap

The trap here is assuming that a single fill or expand argument is enough, when Tkinter also requires the parent's row and column weights to be configured before surplus space is actually distributed.

220
MCQhard

In Python socket programming, what does the 'SO_REUSEADDR' socket option achieve?

A.It speeds up data transmission
B.It allows the address to be reused immediately after the server stops
C.It enables broadcasting on the socket
D.It prevents the socket from closing
AnswerB

SO_REUSEADDR lets the socket bind to a local address still in TIME_WAIT after the server stops, avoiding 'Address already in use' errors. It satisfies the constraint of restarting the server immediately without waiting for the OS to release the port.

Why this answer

It allows the socket to bind to a port that is in a TIME_WAIT state, commonly used to restart servers quickly.

221
MCQhard

You are building a Tkinter application that uses a ttk.Treeview to display a list of employees. Each employee has an ID, name, and department. You want to display the data in columns with headings, and you need the ID column to be hidden. Which approach correctly configures the Treeview to achieve this?

A.Set the Treeview's 'columns' attribute to a list that omits the ID column, and insert items with values that exclude the ID.
B.Set the Treeview's 'show' option to 'tree headings' and set the ID column's width to 0.
C.Use the 'column' method to set the ID column's 'minwidth' to 0 and 'stretch' to False.
D.Set the Treeview's 'show' option to 'headings' and set the 'displaycolumns' attribute to a tuple excluding the ID column.
AnswerD

Setting show='headings' hides the tree column (the first column) and displays only the headings. The displaycolumns attribute specifies which columns are visible; excluding the ID column hides it while keeping the data accessible via item values. This is the correct way to hide a specific column.

Why this answer

The Treeview widget's displaycolumns attribute controls which columns are visible, and show='headings' hides the tree column. By setting displaycolumns to exclude the ID column, you hide it while retaining the data in the item values. The other options either do not hide the column or remove the data entirely.

Exam trap

The trap here is assuming that setting a column's width to zero or removing it from the columns list hides it, when actually displaycolumns is the correct attribute.

222
MCQhard

You are implementing a class that represents a monetary amount. You want the expression amount1 + amount2 to return a new Money instance, and you also want amount1 + 5 to work by treating 5 as a Money with zero cents. However, 5 + amount1 should raise a TypeError. Which implementation achieves this behavior?

A.Define __add__(self, other) and __radd__(self, other) where __radd__ simply calls self.__add__(other).
B.Define __iadd__(self, other) to handle both Money and int, and rely on Python to fall back to __add__ for the + operator.
C.Define __add__(self, other) to handle both Money and int, and define __radd__ to raise TypeError.
D.Define only __add__(self, other) to handle Money and int, and do not define __radd__.
AnswerD

When evaluating 5 + amount1, Python first tries int.__add__(5, amount1), which returns NotImplemented because int does not know Money. It then tries Money.__radd__(amount1, 5). If __radd__ is not defined, Python raises TypeError. Meanwhile amount1 + amount2 and amount1 + 5 work via __add__. This matches the required behavior exactly.

Why this answer

For amount1 + amount2 and amount1 + 5, Python calls Money.__add__, which can handle both Money and int. For 5 + amount1, int.__add__ returns NotImplemented, and Python then looks for Money.__radd__. Since __radd__ is not defined, a TypeError is raised.

This precisely implements the asymmetric addition behavior required.

Exam trap

The trap here is thinking that defining __radd__ is necessary for all addition, when omitting it is exactly what causes the reflected operation to fail as required.

223
MCQeasy

According to PEP 8, what is the maximum recommended length for a line of code?

A.79 characters.
B.80 characters.
C.No limit.
D.120 characters.
AnswerA

PEP 8 sets the maximum line length at 79 characters for code, a limit historically tied to side-by-side diff viewing and terminal widths. This is the specific figure the style guide recommends, satisfying the question's constraint.

Why this answer

PEP 8 suggests limiting lines to 79 characters to allow multiple files to be opened side-by-side.

224
Multi-Selecthard

Which THREE of the following represent common issues when using __slots__?

Select 3 answers
A.Subclasses must define their own __slots__ to avoid creating a __dict__.
B.They make it impossible to add new attributes dynamically.
C.They are incompatible with all decorators.
D.They prevent the use of multiple inheritance.
E.Classes with __slots__ cannot have a __dict__ by default.
AnswersA, B, E

Without redeclaring __slots__ in the subclass, Python reinstates a __dict__ on instances, silently negating the memory savings the parent achieved. This is the classic inheritance pitfall, so subclasses must repeat the declaration to preserve the slot-only layout.

Why this answer

Option A is correct because if a subclass does not declare its own __slots__, Python automatically gives it a __dict__, defeating the memory-saving purpose of __slots__ in the parent class. Option B is correct because __slots__ restricts instances to only the named attributes, so assigning any new attribute not listed raises an AttributeError. Option E is correct because defining __slots__ removes the per-instance __dict__ by default, which is the primary mechanism for saving memory.

Option C is wrong because __slots__ works fine with most decorators such as @property, @staticmethod, and @classmethod. Option D is wrong because __slots__ does not prevent multiple inheritance; it only imposes constraints when multiple bases have non-empty __slots__ with conflicting slot names.

225
Multi-Selecthard

You are writing a Python utility that copies a directory tree to a network share using shutil. You must preserve file metadata and fail loudly if the destination already contains a conflicting file, rather than silently overwriting it. Which TWO shutil features satisfy these requirements? (Choose two.)

Select 2 answers
A.Pass copy_function=shutil.copyfile to shutil.copytree() so existing files are never overwritten.
B.Pass dirs_exist_ok=True to shutil.copytree() so the copy proceeds when the destination directory already exists.
C.Pass copy_function=shutil.copy to shutil.copytree() so only permission bits are carried over.
D.Leave the default behaviour of shutil.copytree() unchanged so that a pre-existing destination path raises FileExistsError.
E.Pass copy_function=shutil.copy2 to shutil.copytree() so metadata such as modification times is preserved.
AnswersD, E

By default copytree() has dirs_exist_ok=False, so if the destination directory already exists it raises FileExistsError before copying anything. That is exactly the fail-loudly behaviour requested when the target share already contains the tree. Combined with a copy_function that preserves metadata, the default conflict handling satisfies the requirement without extra code.

Why this answer

Preserving metadata requires a copy function built on copystat, which copy2 provides, and copytree() exposes this through copy_function. Failing loudly on a pre-existing destination is the default copytree() behaviour, since dirs_exist_ok is False unless explicitly set. Together, copy_function=shutil.copy2 and the default dirs_exist_ok value satisfy both stated requirements.

Exam trap

The trap here is assuming that dirs_exist_ok=True is needed to make copytree() work at all, when it actually suppresses the very error the scenario wants.

Page 2

Page 3 of 4

Page 4

All pages