Courseiva

Certified Associate Python Programmer PCAP (PCAP) — Questions 151169

169 questions total · 3pages · All types, answers revealed

Page 2

Page 3 of 3

151
MCQeasy

A module 'shapes.py' defines several classes: Circle, Square, Triangle. The developer wants to allow users to import only Circle and Square when they use 'from shapes import *'. Which mechanism should be used?

A.Prefix the Triangle class with an underscore to make it private.
B.Use the import_explicit function.
C.Create an __init__.py file in the same directory.
D.Define a list variable named __all__ containing the string names 'Circle' and 'Square'.
AnswerD

Setting __all__ = ['Circle', 'Square'] at the top level of shapes.py explicitly whitelists those two classes for wildcard imports; any other public name, such as Triangle, will be ignored by from shapes import *. This is the canonical Python mechanism for declaring a module's public API, and it is also honored by documentation generators and linters, making the module's intended exports unambiguous.

Why this answer

The `__all__` variable in a module explicitly controls which names are exported when a client uses `from shapes import *`. By setting `__all__ = ['Circle', 'Square']`, only those two classes are imported, while `Triangle` is excluded. This is the standard Python mechanism for restricting wildcard imports.

Exam trap

Python Institute often tests the misconception that an underscore prefix makes a name truly private or that an `__init__.py` file alone controls wildcard imports from a single module, leading candidates to choose A or C instead of the correct `__all__` mechanism.

How to eliminate wrong answers

Option A is wrong because prefixing a name with an underscore (e.g., `_Triangle`) only signals that it is intended for internal use; it does not prevent `from shapes import *` from importing it — Python does not enforce privacy. Option B is wrong because there is no built-in function named `import_explicit` in Python; this is a fabricated term. Option C is wrong because an `__init__.py` file is used to mark a directory as a package and can define its own `__all__`, but it does not control imports from a single module file like `shapes.py`; the question specifies a module, not a package.

152
MCQhard

A class `ServerConfig` has a class attribute `port = 8080`. After deployment, a developer runs `ServerConfig.port = 9090` in one module, and unexpectedly all existing instances now use port 9090. What concept explains this behavior?

A.Instance attributes always override class attributes.
B.The attribute is immutable.
C.Class attributes are shared among all instances of a class.
D.Python uses copy-on-write for attribute access.
AnswerC

Changing a class attribute via the class affects all instances, as they all reference the same attribute.

Why this answer

Class attributes in Python are shared across all instances of a class. When you modify `ServerConfig.port` on the class itself, every instance that accesses `port` via the class (or via an instance that hasn't overridden it) sees the new value. This is fundamental to Python's attribute lookup mechanism: instance attributes shadow class attributes, but if no instance attribute exists, the class attribute is used.

Exam trap

Python Institute often tests the distinction between modifying a class attribute via the class vs. modifying it via an instance; the trap is that candidates think assigning to `instance.port` changes the class attribute, but it actually creates a new instance attribute that shadows the class attribute.

How to eliminate wrong answers

Option A is wrong because instance attributes only override class attributes when they are explicitly set on the instance; they do not cause class-level changes to propagate. Option B is wrong because the attribute `port` is an integer, which is immutable, but immutability does not affect sharing or rebinding of the attribute on the class. Option D is wrong because Python does not use copy-on-write for attribute access; it uses a dynamic lookup chain (instance → class → parent classes) and assignment always modifies the target directly.

153
Multi-Selecthard

Which TWO of the following expressions yield the substring 'Py' from the string s = 'Python'?

Select 2 answers
A.s[0:-4]
B.s[0:2:2]
C.s[-6:-3]
D.s[0:2]
E.s[0:1]
AnswersA, D

Correct: from 0 to -4 (exclusive), which is indices 0 and 1.

Why this answer

S[0:-4] uses negative indexing to slice from index 0 up to (but not including) index -4, which corresponds to the character 'o' (the fifth character from the end). Since 'Python' has length 6, index -4 is the character at position 2 (0-based), so the slice returns characters at indices 0 and 1, which are 'P' and 'y', yielding 'Py'.

Exam trap

Python Institute often tests the interaction between negative indexing and step values, trapping candidates who forget that a step of 2 skips characters or that negative indices count from the end, leading them to select options that return only one character or an incorrect substring.

154
Multi-Selectmedium

Which TWO of the following string methods modify the string in place? (Note: Python strings are immutable.)

Select 2 answers
A.str.join()
B.str.lower()
C.str.upper()
D.str.replace()
E.str.strip()
AnswersB, C

str.lower() returns a new string with all characters lowercased; the original string remains unchanged.

Why this answer

None of the listed string methods modify the string in place because Python strings are immutable. All string methods return a new string rather than altering the original. Therefore, there are no correct options for this question.

Exam trap

The question is designed to test the understanding that strings are immutable. The trap is that candidates may incorrectly believe that methods like replace() or strip() modify the string in place, but in fact no string method modifies the original string.

155
MCQhard

A Python developer is implementing a class that should behave like a sequence and support indexing. Which pair of special methods must be defined to achieve this?

A.__getitem__ and __contains__
B.__setitem__ and __delitem__
C.__iter__ and __next__
D.__getitem__ and __len__
AnswerD

According to the Python data model, a sequence is defined primarily by having a `__len__` method and a `__getitem__` method that accepts integer indices (and optionally slices). Together they give the object a finite length, support `obj[i]` indexing, and implicitly enable iteration via the old-style `__getitem__` fallback. On top of these two, the `collections.abc.Sequence` ABC automatically mixes in `__contains__`, `__iter__`, `__reversed__`, `index`, and `count`, showing how much behavior is derived from just these two methods.

Why this answer

To make a class behave like a sequence and support indexing (e.g., obj[0]), Python requires the __getitem__ method to retrieve items by key. Additionally, the __len__ method is needed to define the length of the sequence, which is used by built-in functions like len() and is part of the sequence protocol. Together, these two methods satisfy the minimal requirements for a sequence-like object that supports indexing.

Exam trap

Python Institute often tests the distinction between the sequence protocol (__getitem__ + __len__) and the iterator protocol (__iter__ + __next__), trapping candidates who think iteration alone enables indexing.

How to eliminate wrong answers

Option A is wrong because __contains__ is used for the 'in' operator (membership testing), not for indexing or sequence behavior. Option B is wrong because __setitem__ and __delitem__ are for mutable sequences that support item assignment and deletion, but indexing (read access) only requires __getitem__; __len__ is still needed for sequence protocol. Option C is wrong because __iter__ and __next__ implement the iterator protocol, which allows iteration but does not provide indexing (e.g., obj[0] would fail without __getitem__).

156
Multi-Selecthard

Which THREE of the following are true about method overriding in Python?

Select 3 answers
A.The subclass method must have the same name.
B.The parent method can be called using `super()`.
C.The `@override` decorator is required.
D.The subclass method can have a different return type.
E.The subclass method can have a different number of parameters.
AnswersA, B, D

Method overriding is based on the same method name as in the parent class.

Why this answer

Method overriding in Python requires the subclass method to have the same name as the parent class method. This is the fundamental rule of overriding — without the same name, the method is not overriding but rather defining a new method. The subclass method replaces the inherited method when called on an instance of the subclass.

Exam trap

Python Institute often tests the misconception that Python requires an `@override` decorator (like Java or C#) or that changing the parameter list is allowed in overriding, when in fact Python uses implicit overriding based solely on method name and expects the same signature for correct polymorphic behavior.

157
MCQeasy

A Python script is written to be used both as a standalone program and as an imported module. Which condition should the script use to execute code only when run directly?

A.if __import__ == '__main__':
B.if __name__ == '__main__':
C.if __name__ == '__module__':
D.if __file__ == 'main':
AnswerB

This is the canonical Python idiom used to determine whether the current file is being run as the top-level script. When the interpreter executes a script directly, it sets the global variable __name__ to the string '__main__'; when the file is imported as a module, __name__ is set to the module's import name instead. The if block therefore only runs for standalone execution, which is exactly what the script intends. This guard also supports running with python -m, where __name__ is also '__main__'.

Why this answer

Python sets the global variable `__name__` to `'__main__'` when the script is executed directly (e.g., `python script.py`). When the script is imported as a module, `__name__` is set to the module's name. The condition `if __name__ == '__main__':` is the standard Python idiom to guard code that should only run in the direct execution context.

Exam trap

Python Institute often tests the exact syntax `if __name__ == '__main__':` and distracts candidates with plausible-sounding but incorrect alternatives like `__import__` or `__module__`, exploiting confusion about Python's special attributes and the difference between module-level and execution-level variables.

How to eliminate wrong answers

Option A is wrong because `__import__` is a built-in function used to import modules programmatically, not a variable that indicates direct execution; comparing it to `'__main__'` is syntactically and semantically invalid. Option C is wrong because `__name__` is never set to `'__module__'`; that string has no special meaning in Python's execution model. Option D is wrong because `__file__` holds the path to the script file, not a string like `'main'`, and it is not used to determine whether the script is run directly or imported.

158
MCQmedium

A class inherits from two parent classes that both have a method with the same name. When calling the method on the child, only one parent's version is executed. What Python mechanism determines which one?

A.Method overloading by signature.
B.Explicit super() call in the child class.
C.Inheritance depth (closest parent wins).
D.Method Resolution Order (MRO).
AnswerD

MRO determines the order of method lookup in multiple inheritance.

Why this answer

Python uses the C3 linearization algorithm to compute the Method Resolution Order (MRO) for a class. When a method is called on an instance, Python searches the MRO from left to right and executes the first implementation it finds. This ensures a consistent and predictable order of inheritance, even in diamond or multiple-inheritance scenarios.

Exam trap

Python Institute often tests the misconception that Python uses 'closest parent wins' or depth-first search, but the actual mechanism is the C3 linearization MRO, which respects base class order and the diamond inheritance pattern.

How to eliminate wrong answers

Option A is wrong because Python does not support method overloading by signature; the last definition of a method in a class overwrites previous ones, and dispatch is based on the object's type, not argument types. Option B is wrong because an explicit super() call is a way to invoke a parent's method from within the child, but it is not the mechanism that determines which parent's method is executed when calling the method directly on the child. Option C is wrong because inheritance depth does not determine which parent's method is called; Python's MRO follows the C3 linearization order, which respects the order of base classes and the diamond pattern, not simply the closest parent.

159
MCQhard

A developer is working on a data pipeline that processes files from untrusted sources. The pipeline should catch and log any exception, but also ensure that sensitive information from the exception (e.g., file paths) is not exposed to end users. Which approach balances security and debugging?

A.Catch the exception and re-raise the same exception.
B.Catch the exception, log it, and suppress it silently.
C.Catch the exception, log the full traceback, then raise a custom generic exception.
D.Catch the exception and print it to the console.
AnswerC

This is the recommended approach because it separates internal diagnostics from user-facing failure information. Logging the full traceback preserves the exact stack, exception types, and local context for developers, while raising a custom generic exception like PipelineProcessingError prevents sensitive implementation details from leaking. Using a custom exception also gives callers a stable interface for retry and alerting logic without coupling them to low-level I/O or network exceptions.

Why this answer

It balances security and debugging: the full traceback is logged for developers (preserving debugging details like file paths), while a custom generic exception is raised to end users, preventing sensitive information from being exposed. This approach follows the principle of least privilege for error handling, ensuring that internal details are not leaked to untrusted sources.

Exam trap

Python Institute often tests the distinction between logging exceptions for debugging versus exposing them to users, and the trap here is that candidates may choose Option A (re-raise) thinking it preserves the exception chain, but they overlook the security requirement to hide sensitive details from end users.

How to eliminate wrong answers

Option A is wrong because re-raising the same exception would expose the original exception's details (including sensitive file paths) to the end user, violating security requirements. Option B is wrong because suppressing the exception silently hides all debugging information from logs, making it impossible for developers to diagnose issues in the pipeline. Option D is wrong because printing the exception to the console exposes sensitive information directly to the user or console output, which is insecure and does not log for debugging.

160
MCQeasy

A developer wants to check if a string ends with a specific suffix. Which method should be used?

A.endswith()
B.index()
C.find()
D.startswith()
AnswerA

The `endswith()` method is the dedicated predicate for suffix testing: it returns `True` only when the final characters of the string exactly match the given suffix, and `False` otherwise. It also accepts optional `start`/`end` slice arguments, which allow you to check only a portion of the string, and it performs a case-sensitive comparison by default (use `casefold()` or lowercasing for case-insensitive checks). Because it returns a boolean directly, it cleanly satisfies the developer's requirement to verify whether the string ends with a specific substring.

Why this answer

The `endswith()` method is specifically designed to check if a string ends with a given suffix, returning a boolean value. This is the correct and most direct approach for the task described, as it avoids manual slicing or comparison.

Exam trap

Python Institute often tests the distinction between `endswith()` and `startswith()`, trapping candidates who confuse prefix and suffix checks, or who mistakenly use `find()` or `index()` which locate substrings anywhere in the string rather than at the end.

How to eliminate wrong answers

Option B is wrong because `index()` returns the lowest index where a substring is found, or raises a ValueError if not found, and does not check for a suffix. Option C is wrong because `find()` returns the lowest index of the substring or -1 if not found, but does not test for the end of the string. Option D is wrong because `startswith()` checks if the string begins with a prefix, not a suffix.

161
MCQhard

Refer to the exhibit. What is the output?

A.2 0 0
B.2 2 2
C.2 1 1
D.0 2 2
AnswerB

The class attribute `count` begins at 0, and each call to `__init__` executes `Sample.count += 1`; with two instantiations before any `print`, the shared class variable is exactly 2. Attribute access on an instance first checks that instance's namespace; since neither `a` nor `b` ever assigns `self.count`, both lookups resolve to the same class-level integer. Thus the three printed lines are identical: 2, 2, 2.

Why this answer

The code defines a class `A` with a class variable `x = 2`, and a class `B` that inherits from `A`. The `display` method prints `self.x`, which first looks up the instance attribute `x`; since no instance attribute is set, it falls back to the class variable `x = 2` from class `A`. The loop creates three instances of `B` and calls `display` on each, so each prints `2` on a separate line, resulting in the output 2, 2, 2.

Exam trap

Python Institute often tests the distinction between class variables and instance attributes, and the trap here is that candidates mistakenly think each instance gets its own copy of `x` or that the loop modifies `x` per iteration, when in fact all instances share the same class variable unless explicitly overridden.

How to eliminate wrong answers

Option A is wrong because it suggests the output is 2, 0, 0, which would require the first instance to access the class variable and subsequent instances to have instance attribute `x` set to 0, but no such assignment occurs. Option C is wrong because it shows 2, 1, 1, which would imply that `x` is being modified or that a different value is assigned per instance, but the class variable remains 2 and no instance attribute is created. Option D is wrong because it shows 0, 2, 2, which would require the first instance to have `x = 0` and the rest to have `x = 2`, but no instance-level assignment or override happens in the code.

162
MCQmedium

A developer tries to modify a string: s = 'hello'; s[0] = 'H'. What happens when this code runs?

A.It changes the string to 'Hello'
B.It raises a TypeError: 'str' object does not support item assignment
C.It creates a new string 'Hello' and assigns it to s
D.It raises an IndexError because index 0 is out of range
AnswerB

Strings in Python are immutable sequences; the assignment `s[0] = 'H'' attempts to mutate the object at index 0, which violates the immutable contract of the `str` type. The interpreter raises a `TypeError` specifically because `str` objects lack a `__setitem__` method, preventing item assignment. This directly satisfies the constraint that strings cannot be modified in-place in Python.

Why this answer

Strings in Python are immutable, meaning their contents cannot be changed after creation. Attempting to assign a new character to an index position (e.g., s[0] = 'H') raises a TypeError: 'str' object does not support item assignment. To modify a string, you must create a new string using slicing or concatenation.

Exam trap

The PCAP exam often tests the immutability of strings by presenting an assignment to an index, tricking candidates who confuse strings with mutable sequences like lists into thinking the string will be modified in place.

How to eliminate wrong answers

Option A is wrong because strings are immutable; assigning to an index does not modify the string in place, so it does not change to 'Hello'. Option C is wrong because Python does not automatically create a new string and reassign s; instead, it raises an error immediately. Option D is wrong because index 0 is valid for a non-empty string like 'hello'; the error is a TypeError, not an IndexError.

163
MCQmedium

A developer is implementing a custom exception for invalid data. Which class should the custom exception inherit from?

A.RuntimeError
B.ArithmeticError
C.BaseException
D.Exception
AnswerD

Exception is the standard, recommended base class for custom exceptions because it is the root of the ordinary error hierarchy, below BaseException but above all built-in exceptions meant for program-level failures. Deriving from it ensures your invalid-data exception is caught by generic `except Exception` handlers, supports chaining with `__cause__`, and clearly communicates that it is an application-level error. This is the convention described in Python's official documentation and followed by most libraries and frameworks.

Why this answer

The `Exception` class is the base class for all built-in, non-system-exiting exceptions in Python. Custom exceptions should inherit from `Exception` (or one of its subclasses) to ensure they are caught by generic `except Exception:` handlers and integrate properly with Python's exception hierarchy, while avoiding the system-exiting exceptions derived from `BaseException`.

Exam trap

The trap here is that candidates often choose `BaseException` thinking it is the most general base class, but Cisco tests the understanding that custom exceptions should inherit from `Exception` to avoid accidentally catching system-exiting exceptions like `KeyboardInterrupt`.

How to eliminate wrong answers

Option A is wrong because `RuntimeError` is a specific built-in exception for errors that do not fit into other categories; inheriting from it would misrepresent the custom exception's semantics and is not the recommended base for all custom exceptions. Option B is wrong because `ArithmeticError` is a narrow base for arithmetic-related errors (e.g., ZeroDivisionError); using it for generic invalid data exceptions would be semantically incorrect and overly restrictive. Option C is wrong because `BaseException` is the root of all exceptions, including system-exiting ones like `SystemExit` and `KeyboardInterrupt`; inheriting from it would cause the custom exception to be caught by `except BaseException:` blocks, which is not intended for user-defined exceptions and can suppress critical system signals.

164
MCQmedium

A team is developing a large Python application with multiple modules. They encounter an ImportError when module A tries to import from module B, and module B tries to import from module A. What is the most likely cause and best practice to resolve this?

A.Use 'from module import *' to bring all names into the namespace.
B.Use lazy imports (inside functions) to defer the import until runtime.
C.Restructure the code to eliminate circular dependencies by extracting shared logic into a third module.
D.Move all imports from module A to the bottom of the file.
AnswerC

Best practice; removes the circular dependency entirely.

Why this answer

Circular imports occur when two modules depend on each other at the top level, causing an ImportError due to incomplete module initialization. The best practice is to restructure the code to eliminate the circular dependency, typically by extracting the shared functionality into a third module that both A and B can import without mutual dependence. This approach aligns with Python's module loading mechanism, which executes a module fully before making its names available for import.

Exam trap

Python Institute often tests the misconception that moving imports or using wildcard imports can fix circular dependencies, when in fact only restructuring the code or using lazy imports (as a temporary workaround) addresses the root cause.

How to eliminate wrong answers

Option A is wrong because 'from module import *' does not resolve circular imports; it can actually worsen the problem by flooding the namespace and still triggers the same ImportError when the circular dependency is present. Option B is wrong because while lazy imports (importing inside functions) can sometimes work around circular imports by deferring the import until after both modules are initialized, it is considered a workaround rather than a best practice, and it can lead to runtime errors if the deferred import is accessed before the other module is fully loaded. Option D is wrong because moving imports to the bottom of the file does not change the order of execution; Python still processes all top-level imports before executing the rest of the module, so the circular dependency remains unresolved.

165
Multi-Selectmedium

Which THREE statements about inheritance in Python are correct?

Select 3 answers
A.A child class inherits all attributes and methods from its parent class.
B.Private attributes (with __) are inherited unchanged.
C.Python supports multiple inheritance.
D.Python supports method overloading based on parameters.
E.The super() function can be used to call a method from a parent class.
AnswersA, C, E

Correct, except for name-mangled ones.

Why this answer

In Python, a child class inherits all non-private attributes and methods from its parent class by default. This includes both data attributes and methods, allowing the child to reuse and extend the parent's behavior without redefinition. Private attributes (with double underscore prefix) are name-mangled to _Classname__attribute, but they are still inherited in the sense that they exist in the child's namespace under the mangled name, though direct access by the original name is restricted.

Exam trap

Python Institute often tests the misconception that private attributes (__name) are completely hidden or not inherited, when in fact they are inherited but name-mangled, and that Python supports method overloading like Java or C++, when it actually relies on default arguments and single method definitions.

166
MCQhard

A developer creates a metaclass 'Meta' that modifies class creation by adding a class attribute 'created_by' set to 'Meta'. Which code snippet correctly defines and uses this metaclass?

A.class Meta(type): def __new__(cls, name, bases, dct): dct['created_by']='Meta'
B.class Meta(type): def __init__(cls, name, bases, dct): dct['created_by']='Meta'
C.def Meta(name, bases, dct): dct['created_by']='Meta'; return type(name, bases, dct)
D.class Meta(type): def __new__(cls, name, bases, dct): dct['created_by']='Meta'; return super().__new__(cls, name, bases, dct)
AnswerD

This correctly overrides `type.__new__`, modifies the mutable namespace dictionary before class construction, and delegates to `super().__new__` to build the class object. Because `super().__new__` copies the entries of `dct` into the new class's `__dict__`, the added `created_by` attribute is present on the finished class. The explicit `return` is essential: without it, no class object would be created at all.

Why this answer

It defines a proper metaclass by subclassing `type` and overriding `__new__`, which is the correct method for modifying the class dictionary before the class is created. The `__new__` method must return the result of `super().__new__(cls, name, bases, dct)` to actually create the class object. Adding `dct['created_by']='Meta'` inside `__new__` ensures the attribute is set during class creation.

Exam trap

Python Institute often tests the distinction between `__new__` and `__init__` in metaclasses, and the trap here is that candidates mistakenly think `__init__` can modify the class dictionary before class creation, or forget that `__new__` must explicitly return the class object.

How to eliminate wrong answers

Option A is wrong because the `__new__` method does not return the newly created class object; without `return super().__new__(...)`, the metaclass returns `None`, causing a `TypeError` when trying to create a class. Option B is wrong because `__init__` is called after the class is already created, so modifying `dct` inside `__init__` does not affect the class's attributes (the dictionary is already used); the correct place to modify the class dictionary is in `__new__`. Option C is wrong because it defines a regular function, not a metaclass; although it can create a class dynamically, it does not define a metaclass that can be used with the `metaclass=Meta` keyword argument in a class statement.

167
MCQhard

An application uses a heavy-weight class DatabaseConnection that establishes a network connection upon instantiation. The class is used in multiple places, and the developer wants to ensure that only one instance of DatabaseConnection exists throughout the application. They implement a Singleton pattern using a class attribute _instance and a class method get_instance(). However, they notice that the network connection is being established multiple times. After debugging, they find that the singleton is not being enforced because the __init__ method is called every time the class is instantiated, even if the same instance is returned. They want to fix this so that the connection is established only once. Which modification should they make?

A.Override __new__ in DatabaseConnection to control instance creation and return the singleton from there, bypassing __init__ on subsequent calls.
B.Use the @staticmethod decorator on get_instance.
C.Use a global variable instead of a class attribute to store the singleton.
D.Move the connection initialization code out of __init__ and into a separate method that is called only once.
AnswerA

Overriding __new__ allows you to return the existing instance before __init__ is called, preventing repeated initialization.

Why this answer

Overriding __new__ allows the developer to control instance creation at the lowest level. By checking if the singleton already exists in __new__, they can return the existing instance without calling __init__ again, thus preventing the network connection from being established multiple times. This is the standard Pythonic way to implement a singleton that avoids reinitialization.

Exam trap

Python Institute often tests the distinction between instance creation (__new__) and instance initialization (__init__), trapping candidates who think that simply returning the same instance from a class method is enough to prevent reinitialization.

How to eliminate wrong answers

Option B is wrong because using @staticmethod on get_instance does not prevent __init__ from being called each time the class is instantiated; it only changes how the method is invoked. Option C is wrong because using a global variable instead of a class attribute does not solve the core issue: __init__ will still be called on every instantiation attempt, re-establishing the connection. Option D is wrong because moving the initialization code to a separate method does not prevent that method from being called multiple times if the singleton pattern is not properly enforced at the instance creation level.

168
MCQeasy

A programmer writes a function that expects a string and returns it reversed. Which code snippet correctly reverses the string 'stressed' to 'desserts'?

A.result = s.reversed()
B.result = s[::-1]
C.s.reverse()
D.result = ''.join(reversed(s))
AnswerB, D

Using extended slice syntax with a step of `-1` creates a reversed copy of the entire string: `s[::-1]` means start at the end, go to the beginning, and step backward by one. This is the most idiomatic and concise way to reverse a string in Python, and it is often preferred for its readability and speed. Since strings are immutable, this operation allocates a new string object containing the characters in reverse order, leaving the original string unchanged.

Why this answer

Both option B and option D correctly reverse the string 'stressed' to 'desserts'. Option B uses slice notation `[::-1]`, which creates a reversed copy of the string by stepping from end to start with a step of -1. This is the most direct and idiomatic way to reverse a string in Python.

Option D uses `''.join(reversed(s))`: `reversed(s)` returns an iterator that yields characters in reverse order, and `join()` concatenates them into a new string. This is also a valid and correct approach. Option A is incorrect because strings do not have a `reversed()` method; `reversed()` is a built-in function.

Option C is incorrect because `.reverse()` is a list method, not a string method, and strings are immutable.

Exam trap

The Python Institute often tests whether candidates know that both slice notation `[::-1]` and the combination of `reversed()` with `join()` are valid ways to reverse a string. Candidates may incorrectly think only slicing is correct or overlook that `reversed()` returns an iterator that requires `join()` to produce a string.

How to eliminate wrong answers

Option A is wrong because `s.reversed()` is not a valid method; the correct built-in is `reversed(s)`, which returns a reverse iterator, not a string. Option C is wrong because `s.reverse()` is a list method, not a string method — strings are immutable and have no `.reverse()` method, so this raises an AttributeError. Option D is wrong because while `''.join(reversed(s))` does produce the reversed string, it is not listed as the correct answer in the given options; the question asks for the snippet that correctly reverses the string, and option B is the direct, idiomatic one-liner.

169
MCQeasy

Which of the following statements about the __init__.py file in a package is true?

A.It is required for a namespace package
B.It is required for a directory to be considered a regular package
C.It cannot contain executable code
D.It is automatically generated by Python
AnswerB

Correct. Without __init__.py, the directory is treated as a namespace package (if on sys.path) or not a package at all.

Why this answer

In Python, a directory containing an `__init__.py` file is recognized as a regular package. This file can be empty or contain initialization code, and its presence is required for the directory to be imported as a package (as opposed to a namespace package). Without it, Python will not treat the directory as a regular package.

Exam trap

Python Institute often tests the misconception that `__init__.py` is always required for any package, but the trap is that namespace packages (introduced in Python 3.3) do not need it, and candidates may confuse regular packages with namespace packages.

How to eliminate wrong answers

Option A is wrong because a namespace package does NOT require an `__init__.py` file; namespace packages are implicitly created for directories that lack `__init__.py` and are used to split a package across multiple directories. Option C is wrong because `__init__.py` can contain executable code, such as package initialization logic or importing submodules, and it is often used to control what is exported via `__all__`. Option D is wrong because `__init__.py` is not automatically generated by Python; it must be created manually by the developer, though some tools or IDEs may create it as a convenience.

Page 2

Page 3 of 3

All pages