Certified Associate Python Programmer PCAP (PCAP) — Questions 451511

511 questions total · 7pages · All types, answers revealed

Page 6

Page 7 of 7

451
MCQhard

A package 'mypkg' has the following structure: mypkg/ __init__.py submod1.py submod2.py The __init__.py file contains: from . import submod1, submod2. A user runs 'import mypkg' and then 'mypkg.submod1.func()'. However, the user got an AttributeError. What is the most likely cause?

A.submod1 is actually a package, not a module, so it cannot be called with 'func()'.
B.The __init__.py should use absolute imports like 'import mypkg.submod1' to make submod1 accessible.
C.The submod1 module does not define a function named 'func'.
D.The user must also run 'from mypkg import submod1' before accessing submod1.
AnswerC

The AttributeError indicates that the attribute 'func' does not exist in submod1.

Why this answer

Option C is correct because the AttributeError indicates that the attribute 'func' was not found on the module object 'submod1'. Since the import statement in __init__.py correctly makes submod1 accessible as mypkg.submod1, the only remaining reason for the error is that submod1.py does not define a function named 'func'. The import mechanism itself is working as intended.

Exam trap

Python Institute often tests whether candidates understand that an AttributeError on a module attribute (like a function) is distinct from an ImportError or ModuleNotFoundError, leading them to incorrectly suspect the import mechanism rather than the missing definition in the module.

How to eliminate wrong answers

Option A is wrong because submod1 is a file (submod1.py) in the package directory, not a subpackage; a package would require a subdirectory with its own __init__.py. Option B is wrong because relative imports (from . import submod1) are perfectly valid and equivalent to absolute imports in this context; both make submod1 accessible as mypkg.submod1. Option D is wrong because after 'import mypkg', the __init__.py already imports submod1 into the mypkg namespace, so 'mypkg.submod1' is directly accessible without an additional import statement.

452
MCQhard

A developer wants to ensure that the 'radius' attribute of a Circle class is always non-negative. Which implementation using @property is correct?

A.class Circle:\n def __init__(self, radius):\n self._radius = radius\n def radius(self):\n return self._radius
B.class Circle:\n def __init__(self, radius):\n self._radius = radius\n @property\n def radius(self):\n return self._radius\n @radius.setter\n def radius(self, value):\n if value < 0:\n raise ValueError\n self._radius = value
C.class Circle:\n def __init__(self, radius):\n self.radius = radius\n @property\n def radius(self):\n return self._radius\n @radius.setter\n def radius(self, value):\n if value < 0:\n raise ValueError\n self._radius = value
D.class Circle:\n def __init__(self, radius):\n self.radius = radius\n @property\n def radius(self):\n return self._radius\n def set_radius(self, value):\n self._radius = value
AnswerC

Uses setter in init, validates always.

Why this answer

Option C is correct because it uses the @property decorator to define a getter and @radius.setter to define a setter that validates the radius value before assignment. The __init__ method correctly assigns to self.radius, which triggers the setter, ensuring the initial value is also validated. This pattern enforces the invariant that radius is always non-negative.

Exam trap

Python Institute often tests the subtlety that __init__ must use the property setter (self.radius = radius) rather than directly assigning to the backing attribute (self._radius = radius) to ensure validation applies to the initial value as well.

How to eliminate wrong answers

Option A is wrong because it lacks the @property decorator, so radius is a plain method, not a property; accessing circle.radius would return a bound method, not the stored value. Option B is wrong because __init__ assigns to self._radius directly, bypassing the setter validation, so an initial negative radius would be accepted. Option D is wrong because it defines a set_radius method instead of using @radius.setter, so the property is read-only and assignment to circle.radius would raise an AttributeError.

453
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

These are the minimum to support indexing and length.

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__).

454
MCQmedium

A class named Counter has a class variable count and an instance method increment. The method is defined as def increment(self): Counter.count += 1. What will be the output after executing the following code? c1 = Counter(); c2 = Counter(); c1.increment(); c2.increment(); print(Counter.count, c1.count, c2.count)

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

Both c1 and c2 refer to the same class variable count.

Why this answer

Option A is correct because the class variable `count` is shared across all instances of the `Counter` class. The `increment` method modifies `Counter.count` directly, so after two calls, `Counter.count` becomes 2. Since `c1.count` and `c2.count` refer to the same class variable (they do not have instance attributes shadowing it), both instances reflect the same value of 2.

Exam trap

Python Institute often tests the distinction between class variables and instance variables, trapping candidates who mistakenly think each instance gets its own copy of the class variable or that `self.count` would create an instance attribute instead of modifying the class variable.

How to eliminate wrong answers

Option B is wrong because it assumes each instance has its own `count` attribute that increments independently, but the code modifies the class variable, not instance attributes. Option C is wrong because it suggests only one increment occurred, but two calls to `increment()` were made. Option D is wrong because it implies no increment happened at all, ignoring the two calls to `increment()`.

455
Multi-Selecteasy

Which TWO of the following are built-in Python exceptions?

Select 2 answers
A.CustomException
B.InputError
C.ValueError
D.FileNotFoundError
E.FileReadError
AnswersC, D

Built-in exception for invalid value.

Why this answer

ValueError (C) is a built-in Python exception that is raised when a built-in operation or function receives an argument with the correct type but an inappropriate value, such as int('abc'). FileNotFoundError (D) is a built-in exception in Python 3, raised when a file or directory is requested but does not exist, commonly encountered during file I/O operations like open().

Exam trap

Python Institute often tests the distinction between built-in exceptions and user-defined or non-existent exceptions, and the trap here is that candidates may confuse InputError or FileReadError with real built-in exceptions like EOFError or OSError, or assume that any error related to input or files must be a built-in exception.

456
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

Option A is correct because 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.

457
Multi-Selectmedium

Which TWO statements about the __init__.py file in a Python package are true?

Select 2 answers
A.It must contain at least one import statement to be valid.
B.It is mandatory for all packages, including namespace packages.
C.It prevents submodules from being imported directly.
D.It can define the __all__ list to control what is exported with 'from package import *'.
E.It is executed when the package is first imported.
AnswersD, E

Yes, __all__ can be defined there.

Why this answer

Option D is correct because the `__all__` list in `__init__.py` explicitly defines the public API of a package, controlling which names are exported when a client uses `from package import *`. This is a standard Python mechanism to prevent unintended internal modules from being exposed.

Exam trap

Python Institute often tests the misconception that `__init__.py` is mandatory for all packages, including namespace packages, and that it must contain code to be valid, when in fact it can be empty and is optional for namespace packages.

458
MCQhard

Which of the following expressions raises a ValueError?

A.'abc'.index('a')
B.'abc'.find('d')
C.'abc'.rfind('d')
D.'abc'.index('d')
AnswerD

Substring not found; raises ValueError.

Why this answer

Option D is correct because calling `'abc'.index('d')` raises a `ValueError` when the substring is not found. The `str.index()` method in Python is designed to raise this exception for missing substrings, unlike `str.find()` and `str.rfind()`, which return -1.

Exam trap

Python Institute often tests the subtle difference between `index()` (which raises an exception) and `find()`/`rfind()` (which return -1), trapping candidates who assume all substring search methods behave identically on failure.

How to eliminate wrong answers

Option A is wrong because `'abc'.index('a')` successfully finds the substring 'a' at index 0, so no exception is raised. Option B is wrong because `'abc'.find('d')` returns -1 when the substring is not found, as per Python's string method behavior. Option C is wrong because `'abc'.rfind('d')` also returns -1 for a missing substring, following the same convention as `find()`.

459
MCQeasy

A developer runs pip install requests. Later, they need to find out where the module is installed on the system. Which command shows the location?

A.python -c "print(requests.__path__)"
B.pip list --path
C.python -c "import requests; print(requests.__file__)"
D.pip show requests
AnswerC

__file__ contains the path of the module.

Why this answer

Option C is correct because after importing a module in Python, its `__file__` attribute contains the absolute path to the module's `.py` file (or compiled `.pyc` file). The command `python -c "import requests; print(requests.__file__)"` first imports the module, then prints the location where Python found it, which is the exact installation path on the system.

Exam trap

Python Institute often tests the distinction between module attributes (`__file__`) and package attributes (`__path__`), and the trap here is that candidates confuse `pip show` (which shows metadata) with a command that reveals the filesystem location.

How to eliminate wrong answers

Option A is wrong because `__path__` is an attribute of packages (directories with `__init__.py`), not of regular modules like `requests`; using it would raise an `AttributeError` unless the module is a namespace package. Option B is wrong because `pip list --path` is not a valid pip command; `pip list` shows installed packages but does not have a `--path` flag to display installation locations. Option D is wrong because `pip show requests` displays metadata (version, author, dependencies) but does not show the filesystem path where the module is installed.

460
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

Correctly checks if the script is the main program.

Why this answer

Option B is correct because 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.

461
Multi-Selecthard

Refer to the exhibit. Which THREE statements about the class hierarchy are correct?

Select 3 answers
A.D does not have a method named 'method'
B.Calling D().method() returns 'B'
C.The super() call in B would call C.method
D.The MRO of D is ['D', 'B', 'C', 'A', 'object']
E.Class C is a subclass of A
AnswersB, D, E

B is first in MRO after D.

Why this answer

Option B is correct because when `D().method()` is called, Python's MRO (Method Resolution Order) for class D is `['D', 'B', 'C', 'A', 'object']`. Since class D does not define `method`, Python looks up the MRO and finds `method` first in class B. The `return 'B'` in B's `method` is executed, so the call returns 'B'.

Exam trap

Python Institute often tests the misconception that `super()` always calls the immediate parent class, when in fact it follows the MRO of the runtime instance, which can skip or reorder classes in multiple inheritance scenarios.

462
Multi-Selecteasy

Which two of the following are valid ways to create a multiline string in Python source code? (Choose two.)

Select 2 answers
A.s = "Line1\nLine2"
B.s = 'Line1' 'Line2'
C.s = """Line1\nLine2"""
D.s = '''Line1\nLine2'''
E.s = 'Line1\nLine2'
AnswersC, D

Triple quotes allow the string to span multiple lines, even with escape sequences.

Why this answer

Triple-quoted strings (options B and E) allow literal newlines in the source code. Options A and D use escape sequences but are single-line in source. Option C is concatenation on one line.

463
Matchingmedium

Match each variable scope to its description.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Inside a function

At module level

In outer function (nested)

Predefined names in Python

Variable from enclosing scope (not global)

Why these pairings

Python variable scopes (LEGB rule).

464
MCQmedium

A developer wants to ensure that a file is always closed, even if an exception occurs, without using the 'with' statement. Which approach correctly achieves this?

A.f = open('file.txt'); try: ... except: ... else: f.close()
B.f = open('file.txt'); try: ... finally: f.close()
C.if f.closed: pass else: f.close()
D.try: f = open('file.txt'); ... except: pass; finally: f.close()
AnswerB

Correct: finally ensures close.

Why this answer

Option B is correct because the `finally` block is guaranteed to execute regardless of whether an exception occurs in the `try` block. This ensures that `f.close()` is always called, properly releasing the file resource. The `with` statement is not used, but the `try...finally` construct provides the same deterministic cleanup behavior.

Exam trap

Python Institute often tests the distinction between `else` and `finally` in exception handling, trapping candidates who think `else` runs unconditionally or that placing `open()` inside the `try` block is safe without checking for assignment failure.

How to eliminate wrong answers

Option A is wrong because the `else` block only runs if no exception occurs; if an exception is raised, `f.close()` is never executed, leaving the file open. Option C is wrong because it references `f.closed` before `f` is defined in the given code snippet, and even if defined, it does not guarantee closure after an exception — it is a conditional check, not a cleanup mechanism. Option D is wrong because the `except` block contains `pass`, which silently swallows exceptions, and although `finally` runs, the `try` block includes the `f = open(...)` statement; if `open()` itself raises an exception (e.g., file not found), `f` is never assigned, causing a `NameError` in the `finally` block when trying to call `f.close()`.

465
Multi-Selecteasy

Which TWO of the following operations can be performed on a string?

Select 2 answers
A.Extend with .extend()
B.Append with .append()
C.Pop with .pop()
D.Slicing with [::]
E.Concatenation with +
AnswersD, E

Strings support slicing to extract substrings.

Why this answer

Option D is correct because string slicing with the syntax `[start:stop:step]` (e.g., `[::]`) is a built-in operation for strings in Python, allowing extraction of substrings. Option E is correct because the `+` operator performs string concatenation, creating a new string by joining two strings together.

Exam trap

Python Institute often tests the distinction between mutable (list) and immutable (string) types, leading candidates to incorrectly assume that list methods like `.append()`, `.extend()`, and `.pop()` also work on strings.

466
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.

467
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

Logs details for developers, raises a safe exception to users.

Why this answer

Option C is correct because 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.

468
Multi-Selecthard

Which THREE of the following are recommended techniques to avoid circular imports in Python?

Select 3 answers
A.Manually check sys.modules before importing.
B.Use the __all__ variable to control what is exported.
C.Restructure the code to move shared functionality into a separate module.
D.Use lazy imports inside functions or methods.
E.Use absolute imports instead of relative imports.
AnswersC, D, E

Eliminates the circular dependency entirely.

Why this answer

Option C is correct because moving shared functionality into a separate module breaks the circular dependency chain at the import level. When two or more modules depend on each other, Python's import system may raise an ImportError or produce partially initialized modules, leading to AttributeError. Restructuring eliminates the mutual dependency by creating a common module that both original modules can import safely.

Exam trap

Python Institute often tests the misconception that __all__ or sys.modules manipulation are valid solutions for circular imports, when in fact they are either irrelevant or dangerous workarounds that do not address the root cause.

469
Multi-Selecthard

Which TWO of the following are true about importing modules using the import statement?

Select 2 answers
A.The module is executed only once on the first import.
B.Relative imports can be used in scripts executed as the main module.
C.Importing a module with a different name using 'as' creates a copy of the module.
D.Circular imports always cause an ImportError.
E.Importing a module adds it to sys.modules.
AnswersA, E

Subsequent imports retrieve the cached module.

Why this answer

Option A is correct because Python caches imported modules in the sys.modules dictionary. When a module is imported for the first time, it is executed and its code is stored; subsequent imports of the same module simply retrieve the cached object from sys.modules without re-executing the module's code. This ensures that module-level initialization runs only once, preventing side effects like repeated resource allocation or redefinition of global variables.

Exam trap

Python Institute often tests the misconception that 'import module as alias' creates a separate copy of the module, when in reality it only creates an additional reference to the same module object in sys.modules.

470
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

endswith() returns True if the string ends with the given suffix.

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.

471
MCQmedium

A programmer wants to catch both `FileNotFoundError` and `PermissionError` with a single except clause. Which tuple is correct?

A.except (FileNotFoundError, PermissionError):
B.except FileNotFoundError, PermissionError:
C.except OSError:
D.except [FileNotFoundError, PermissionError]:
AnswerA

Correct tuple syntax.

Why this answer

Option A is correct because Python's exception handling syntax allows a tuple of exception types in a single `except` clause, enabling the programmer to catch multiple exception types with the same handler. Both `FileNotFoundError` and `PermissionError` are subclasses of `OSError`, but using the tuple explicitly catches only those two specific exceptions, not all `OSError` subtypes.

Exam trap

Python Institute often tests the distinction between the correct tuple syntax `except (Exc1, Exc2):` and the incorrect comma-separated syntax `except Exc1, Exc2:` (which is a Python 2 relic), or the overly broad `except OSError:` that catches more than intended.

How to eliminate wrong answers

Option B is wrong because it uses a comma instead of parentheses, which is the old Python 2 syntax for catching exceptions and assigning the exception instance to a variable; in Python 3, this raises a `SyntaxError`. Option C is wrong because while `FileNotFoundError` and `PermissionError` are both subclasses of `OSError`, catching `OSError` would also catch many other unrelated exceptions (e.g., `FileExistsError`, `IsADirectoryError`), which is not what the programmer wants. Option D is wrong because square brackets denote a list, not a tuple; Python's `except` clause requires a tuple of exception types, and using a list will raise a `TypeError`.

472
MCQeasy

A programmer wants to use the sqrt function from the math module. Which import statement is most efficient?

A.from math import sqrt
B.import math.sqrt
C.from math import *
D.import math
AnswerA

Imports only the needed function.

Why this answer

Option A is correct because `from math import sqrt` imports only the `sqrt` function directly into the current namespace, avoiding unnecessary memory usage and name collisions. This is the most efficient approach when you need only a single function from a module, as it minimizes the import overhead and keeps the namespace clean.

Exam trap

Python Institute often tests the misconception that `import module.submodule` is valid syntax, when in fact Python requires `from module import submodule` or `import module` and then attribute access; the trap here is that candidates may think `import math.sqrt` works like a package import, but `math` is a module, not a package, and `sqrt` is a function, not a submodule.

How to eliminate wrong answers

Option B is wrong because `import math.sqrt` is invalid syntax; the dot operator is used for attribute access, not for import statements, and Python will raise a SyntaxError. Option C is wrong because `from math import *` imports all names from the math module into the current namespace, which can cause unintended name clashes and wastes memory by loading functions you don't need. Option D is wrong because `import math` imports the entire module, requiring you to call `math.sqrt()` each time, which is less efficient in terms of namespace lookup and memory if you only need the `sqrt` function.

473
MCQhard

A developer needs to format a floating-point number 123.456789 with exactly 2 decimal places and a width of 10 characters, right-aligned. Which format specifier accomplishes this?

A.:.2f
B.:10.2g
C.:10.2e
D.:10.2f
AnswerD

Width 10, precision 2, fixed-point formatting.

Why this answer

Option C is correct because the format specifier '10.2f' means width 10, precision 2, fixed-point. Option A is wrong because '.2f' has no width. Option B is wrong because '10.2e' uses scientific notation.

Option D is wrong because '10.2g' uses general format which may not always show 2 decimal places.

474
Multi-Selectmedium

Which TWO of the following are valid ways to define a class method in Python? (Select exactly two.)

Select 2 answers
A.def my_method(cls): pass my_method = classmethod(my_method)
B.class MyClass: def my_method(cls): pass
C.def my_method(self): pass
D.@staticmethod def my_method(cls): pass
E.@classmethod def my_method(cls): pass
AnswersA, E

Alternative way to apply classmethod decorator.

Why this answer

Option A is correct because it manually applies the `classmethod()` built-in function to a regular function, converting it into a class method. This is a valid, though less common, way to define a class method, as the `classmethod` descriptor wraps the function so that the first argument passed is the class (`cls`), not an instance.

Exam trap

Python Institute often tests the distinction between the explicit `classmethod()` call and the decorator syntax, and the trap here is that candidates may think only the `@classmethod` decorator is valid, overlooking the manual `classmethod()` function call as an equally valid alternative.

475
MCQmedium

A developer has a project structure with 'my_package/' containing '__init__.py', 'module_a.py', and 'sub_package/' (with its own '__init__.py'). They want to import function 'foo' from 'module_a' inside a script in 'sub_package' using a relative import. Which statement is correct?

A.from .module_a import foo
B.from ..module_a import foo
C.from my_package.module_a import foo
D.from ..my_package.module_a import foo
AnswerB

Two dots go to the parent package (my_package) where module_a resides.

Why this answer

Option B is correct because the script is inside 'sub_package/', which is one directory level below 'my_package/'. To import from 'module_a' (located in the parent package 'my_package'), a relative import uses '..' to go up one package level, then specifies the module name. Thus, 'from ..module_a import foo' correctly navigates the package hierarchy.

Exam trap

Python Institute often tests the distinction between relative and absolute imports, and the trap here is that candidates confuse the dot notation ('.' for current package, '..' for parent) with file system paths, leading them to pick 'from .module_a import foo' thinking it refers to the parent directory.

How to eliminate wrong answers

Option A is wrong because '.module_a' refers to a module within the same package ('sub_package'), not the parent package 'my_package'. Option C is wrong because it uses an absolute import path, which is valid but not a relative import as required by the question. Option D is wrong because '..my_package.module_a' incorrectly goes up one level and then tries to access 'my_package' again, which is already the parent package, leading to a double reference.

476
MCQeasy

A junior developer is building a script to convert user-provided headlines into URL slugs. The slug should contain only lowercase alphanumeric characters and single hyphens between words, with no leading or trailing hyphens. For example, 'Hello World! How are you?' should become 'hello-world-how-are-you'. The current code is: slug = input_string.lower().replace(' ', '-').replace('!', '').replace('?', ''). However, this produces multiple hyphens when there are multiple spaces, and trailing hyphens if the string ends with punctuation. The developer needs to modify the code to handle these issues reliably. Which of the following approaches is the most robust and efficient?

A.Use string.replace multiple times to replace punctuation and then replace multiple spaces with a single hyphen
B.Use re.sub(r'[^a-z0-9]+', '-', input_string.lower()).strip('-')
C.words = [w.strip('!?.,') for w in input_string.lower().split()]; slug = '-'.join(filter(None, words))
D.Iterate over each character, build a list of allowed characters, and join with hyphens
AnswerC

Cleanly splits on whitespace, strips punctuation, filters empties, and joins with hyphen.

Why this answer

Option B splits the string into words (using split() which handles multiple spaces), strips punctuation from each word, filters out empty strings, and joins with a single hyphen. This ensures no multiple hyphens or leading/trailing hyphens. Option A uses regex but is more complex and may still have edge cases.

Option C uses replace with regex but similar issues. Option D is a manual loop that is less efficient and error-prone.

477
MCQhard

A developer writes a function to reverse a string: def reverse_str(s): return s[::-1]. Which of the following statements about this function is true?

A.It only works for strings with even length
B.It returns a new reversed string
C.It modifies the original string
D.It raises an error if s is empty
AnswerB

Correct: s[::-1] creates a new reversed string without modifying the original.

Why this answer

Strings are immutable in Python, so slicing returns a new string. The step -1 reverses the sequence. The function works for any string, including empty strings.

478
Multi-Selectmedium

Consider the following directory structure: project/ main.py pkg/ __init__.py mod1.py subpkg/ __init__.py mod2.py From main.py, you write: from pkg.subpkg import mod2 Which THREE of the following are true regarding relative imports?

Select 3 answers
A.Relative imports only work when the importing module is part of a package.
B.In mod2.py, you can use `from .. import mod1` to import mod1 from pkg.
C.In main.py, you can use `from . import pkg` to import pkg.
D.A directory must contain an __init__.py file to be a package for relative imports to function.
E.The dot notation is interpreted based on the module's __name__ and __package__ attributes.
AnswersA, B, E

They require __package__ to be set properly.

Why this answer

Option A is correct because relative imports (using dot notation like `..` or `.`) are only valid when the importing module is itself part of a package. This is because relative imports rely on the `__package__` attribute to resolve the import path; if the module is not inside a package (e.g., a top-level script), `__package__` is `None` or empty, and relative imports will raise an `ImportError`.

Exam trap

Python Institute often tests the misconception that relative imports can be used from any module, including top-level scripts, or that `__init__.py` is always mandatory for a package; the trap here is that candidates may think `main.py` can use `from . import pkg` because it is in the same directory as `pkg/`, ignoring that relative imports require the importing module to be part of a package.

479
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

All calls refer to the same class variable.

Why this answer

Option B is correct because 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.

480
MCQmedium

Refer to the exhibit. What will happen when the code is executed?

A.It prints None
B.It raises a TypeError
C.It raises an AttributeError
D.It prints 10
AnswerC

obj.__x does not exist due to name mangling.

Why this answer

The code attempts to call a method or access an attribute that does not exist on the object. In Python, when you try to access an attribute or method that is not defined on an object, an AttributeError is raised. Option C is correct because the exhibit shows an attempt to call a non-existent method or attribute on an instance, which triggers AttributeError.

Exam trap

Python Institute often tests the distinction between AttributeError and TypeError, trapping candidates who confuse missing methods with type mismatches.

How to eliminate wrong answers

Option A is wrong because the code does not contain a return statement that would produce None; instead, it raises an exception. Option B is wrong because a TypeError occurs when an operation or function is applied to an object of inappropriate type, not when a missing attribute is accessed. Option D is wrong because the code does not print 10; it raises an exception before any print statement could execute.

481
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 are immutable, so item assignment is not allowed.

Why this answer

Option A is correct because strings are immutable; assigning to an index raises TypeError. Option B is wrong because it does not assign a new string; assignment to index fails. Option C is wrong because it raises an error, it does not succeed.

Option D is wrong because the error is TypeError, not IndexError.

482
MCQeasy

A developer needs to extract the file extension from a string like 'report.pdf'. Which string method is most appropriate?

A.str.find('.')
B.str.split('.')[-1]
C.str.partition('.')[2]
D.str.rstrip('.pdf')
AnswerB

Splits by '.' and returns the last element, which is the extension.

Why this answer

Option B is correct because `str.split('.')[-1]` splits the string at each dot and returns the last element, which is the file extension. This method works reliably for simple cases like 'report.pdf' and is a common Python idiom for extracting extensions.

Exam trap

Python Institute often tests the distinction between `partition()` and `split()` — candidates mistakenly choose `partition()` because it seems simpler, but they overlook that `partition()` only splits on the first occurrence, making it unsuitable for extensions in filenames with multiple dots.

How to eliminate wrong answers

Option A is wrong because `str.find('.')` returns the index of the first dot, not the extension itself. Option C is wrong because `str.partition('.')[2]` returns everything after the first dot, which works for 'report.pdf' but fails for strings with multiple dots (e.g., 'archive.tar.gz' returns 'tar.gz' instead of 'gz'). Option D is wrong because `str.rstrip('.pdf')` removes trailing characters that match any character in '.pdf' (not the exact substring), so it would incorrectly strip 'f' from 'report.pd' or remove more than intended.

483
MCQhard

A log analysis script needs to extract all IP addresses from a string. The IPs are in dotted-decimal format. Which regex pattern will correctly extract them?

A.r'[0-9]+\. [0-9]+\.[0-9]+\.[0-9]+'
B.r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
C.r'(?:[0-9]{1,3}\.){3}[0-9]{1,3}'
D.r'\d+\.\d+\.\d+\.\d+'
AnswerC

Matches three groups of 1-3 digits followed by dot, then one more group. Does not validate range beyond 999, but typical for IP extraction.

Why this answer

Option C is correct because it uses a non-capturing group `(?:...)` to repeat the pattern `[0-9]{1,3}\.` exactly three times, followed by a final octet `[0-9]{1,3}`. This matches the dotted-decimal structure of an IPv4 address (four octets, each 1–3 digits, separated by dots) without introducing extra spaces or overly permissive digit counts, and it avoids capturing unnecessary groups.

Exam trap

Python Institute often tests the distinction between capturing and non-capturing groups, and the trap here is that candidates see option B (which also works) and assume it is correct, but the exam expects the more efficient non-capturing group syntax (C) as the proper regex for extraction without unnecessary overhead.

How to eliminate wrong answers

Option A is wrong because it includes a space after the first dot (`\. [0-9]+`), which would not match a properly formatted IP address (e.g., it would require '192. 168.1.1' instead of '192.168.1.1'). Option B is wrong because it uses `\d{1,3}` which matches 1 to 3 digits, but this pattern is identical in function to C; however, B is not the correct answer because the question specifically expects the non-capturing group syntax (C) as the correct regex, and B is technically valid but not the intended answer (the trap is that B also works but C is more efficient and matches the PCAP emphasis on non-capturing groups). Option D is wrong because `\d+` matches one or more digits with no upper limit, allowing octets like '9999' or '12345', which are invalid for IPv4 (each octet must be 0–255, and while regex alone cannot enforce the numeric range, `\d+` is too permissive and would match malformed addresses).

484
MCQeasy

A small web application allows users to download files from a server. The code uses open() without any exception handling. When a user requests a non-existent file, the server crashes with a traceback and returns a 500 Internal Server Error to the client. The team needs to modify the code to handle this situation gracefully: if the file does not exist, the application should return a 404 Not Found response (by calling a function send_404()). The application should not catch unrelated exceptions like KeyboardInterrupt. Which modification is the most appropriate?

A.Wrap the entire request handling in a try-except block catching Exception, and if any exception occurs, call send_500().
B.Check if the file exists using os.path.exists before opening, and if not, call send_404().
C.Wrap the open() call in a try-except block catching OSError, and in the except block call send_404().
D.Wrap the open() call in a try-except block catching FileNotFoundError, and in the except block call send_404().
AnswerD

Specifically handles the missing file case without catching unrelated errors.

Why this answer

Option D is correct because it catches the specific exception raised when a file is not found (FileNotFoundError), which is a subclass of OSError. This allows the code to return a 404 response for missing files while not catching unrelated exceptions like KeyboardInterrupt, as required. The except block calls send_404() to handle the missing file gracefully without crashing the server.

Exam trap

Python Institute often tests the distinction between catching a specific exception (FileNotFoundError) versus its parent class (OSError), and the trap here is that candidates may choose the broader OSError (Option C) thinking it covers all file-related errors, but that would incorrectly handle permission or other OS errors as 404s.

How to eliminate wrong answers

Option A is wrong because it catches all exceptions (including KeyboardInterrupt) and calls send_500(), which does not distinguish between a missing file and other errors, violating the requirement to not catch unrelated exceptions. Option B is wrong because it introduces a race condition: between checking os.path.exists and opening the file, the file could be deleted or renamed, leading to an unhandled exception. Option C is wrong because catching OSError is too broad; it would catch other OS-related errors (e.g., permission denied) and incorrectly return a 404, when the requirement is to only handle non-existent files with a 404 response.

485
MCQeasy

A class has an attribute that should be computed on access and cached for subsequent accesses. Which pattern is most appropriate?

A.Use __slots__ to define the attribute.
B.Use a custom descriptor that caches the value in the instance's __dict__.
C.Use a @classmethod to compute the value.
D.Use a @staticmethod to compute the value.
AnswerB

A descriptor can compute on first access and store the result for subsequent calls.

Why this answer

Option B is correct because a custom descriptor with a __get__ method can compute the attribute value on first access and store it in the instance's __dict__ for subsequent accesses. This pattern, often called a cached property, ensures the computation happens only once per instance, which is exactly what the question requires.

Exam trap

Python Institute often tests the distinction between descriptors that compute on every access versus those that cache, and the trap here is that candidates confuse __slots__ (memory optimization) with caching, or think that class-level methods like @classmethod can somehow provide per-instance caching.

How to eliminate wrong answers

Option A is wrong because __slots__ is used to restrict the attributes an instance can have and to save memory by preventing the creation of a __dict__; it does not provide any caching or lazy computation mechanism. Option C is wrong because a @classmethod operates on the class itself, not on an instance, and cannot cache per-instance computed values. Option D is wrong because a @staticmethod is essentially a regular function inside the class namespace, with no access to the instance or class, and thus cannot compute or cache instance-specific attributes.

486
Multi-Selectmedium

Which THREE of the following are valid escape sequences in Python strings?

Select 3 answers
A.\g
B.\t
C.\h
D.\r
E.\n
AnswersB, D, E

Valid: tab.

Why this answer

Option B is correct because \t is the standard escape sequence for a horizontal tab character in Python strings. Escape sequences in Python begin with a backslash followed by a specific character, and \t is defined in the Python language specification (similar to C) to represent the ASCII tab character (0x09).

Exam trap

Python Institute often tests the distinction between valid escape sequences and invalid ones that are silently treated as literal characters, leading candidates to mistakenly think any backslash-letter combination is valid.

487
MCQmedium

Refer to the exhibit. What will be the output?

A.None
B.0
C.AttributeError
D.10
AnswerC

AttributeError because `__private` is mangled to `_MyClass__private` and cannot be accessed directly from outside.

Why this answer

Option C is correct because the code attempts to call `obj.get_value()` on an instance of `MyClass`, but `MyClass` does not define a `get_value` method. In Python, this raises an `AttributeError` since the attribute is not found on the object or its class. The error occurs at runtime, not during compilation, because Python dynamically looks up attributes.

Exam trap

Python Institute often tests the misconception that a missing method will silently return `None` or a default value, but in Python, accessing an undefined attribute on an object always raises an `AttributeError` unless a `__getattr__` method is defined to handle it.

How to eliminate wrong answers

Option A is wrong because the code does produce output—specifically, an exception is raised, so the program does not silently produce 'None'. Option B is wrong because the code does not return or print the integer 0; there is no default value mechanism that would yield 0 for a missing method. Option D is wrong because the code does not execute a method that returns 10; the `get_value` method is never defined, so no value of 10 is ever produced.

488
Multi-Selecthard

In a performance-critical application, you need to concatenate many strings in a loop. Which TWO approaches are most efficient?

Select 2 answers
A.Using the % formatting operator
B.Using the join() method on a list
C.Using the += operator
D.Using the + operator
E.Using StringIO from the io module
AnswersB, E

Efficiently builds the string in one pass.

Why this answer

Using join() on a list of strings is efficient because it allocates the final string once. Using StringIO from the io module builds a mutable buffer, also efficient. The += and + operators create a new string object for each concatenation, leading to O(n^2) time. % formatting also creates a new string each iteration.

489
MCQeasy

A developer defines a subclass 'Dog' that overrides the '__init__' method of the parent class 'Animal'. The parent class __init__ sets a 'species' attribute. Which code ensures the parent __init__ is called correctly in Python 3?

A.class Dog(Animal): def __init__(self, name): super().__init__(); self.name = name
B.class Dog(Animal): def __init__(self, name): self.name = name
C.class Dog(Animal): def __init__(self, name): super().__init__(name); self.name = name
D.class Dog(Animal): def __init__(self, name): Animal.__init__(self); self.name = name
AnswerA

super().__init__() calls the parent __init__ without arguments if parent doesn't require any.

Why this answer

Option A is correct because it uses `super().__init__()` without arguments, which calls the parent `Animal.__init__` method as per Python 3's cooperative multiple inheritance model. Since the parent `__init__` sets `species` without requiring any parameters, this ensures the `species` attribute is initialized before `self.name` is set in the subclass.

Exam trap

Python Institute often tests the misconception that `super().__init__()` must always pass the subclass's arguments to the parent, leading candidates to choose Option C, but the correct behavior depends on the parent's signature, not a blanket rule.

How to eliminate wrong answers

Option B is wrong because it completely omits a call to the parent `__init__`, so the `species` attribute is never set, leaving the object without that inherited attribute. Option C is wrong because it passes `name` to `super().__init__(name)`, but the parent `__init__` does not accept a `name` parameter, causing a `TypeError`. Option D is wrong because while `Animal.__init__(self)` works technically, it bypasses Python's MRO and is not the recommended Python 3 idiom; more critically, it still correctly calls the parent init, but the question asks for the 'correct' Python 3 approach, which is `super()`, not direct parent class referencing.

490
MCQmedium

A developer defines a class hierarchy with multiple inheritance: class A, class B(A), class C(A), class D(B,C). The method 'm' is defined only in A. What is the method resolution order for D according to the C3 linearization algorithm?

A.D -> B -> A -> object
B.D -> B -> C -> A -> object
C.D -> B -> C -> A
D.D -> B -> A -> C
AnswerC

C3 linearization for D(B,C) yields D, B, C, A.

Why this answer

C is correct because the C3 linearization algorithm merges the linearizations of parent classes while preserving local precedence order and monotonicity. For class D(B, C), the linearization is D + merge(L(B), L(C), [B, C]). L(B) = B, A, object; L(C) = C, A, object.

Merging yields D, B, C, A, object (object is often omitted in option lists). This respects that B precedes C in D's bases and that A appears after both B and C.

Exam trap

Python Institute often tests the misconception that the MRO follows a simple depth-first left-to-right order, causing candidates to pick option A (D, B, A, C) or D (D, B, A, C) instead of the correct C3 merge result that respects the order of parent classes and their linearizations.

How to eliminate wrong answers

Option A is wrong because it omits class C entirely, violating the local precedence order of D's bases (B, C) and the C3 merge rule that includes all parent classes. Option B is wrong because it places object at the end, which is technically correct but the given option list omits 'object' — however the core error is that it includes object while the correct answer (C) does not; more importantly, option B's order (D, B, C, A, object) is actually the full correct MRO, but the question's answer choices treat 'object' as optional, so option C is the intended correct answer without object. Option D is wrong because it places A before C, violating the C3 rule that C must appear before A since C inherits from A and the merge must preserve the order from C's linearization (C, A).

491
Multi-Selecthard

Which TWO of the following are valid ways to define a class attribute that is shared among all instances?

Select 2 answers
A.Assign the attribute inside a classmethod using cls.
B.Assign the attribute inside a staticmethod.
C.Use the @property decorator.
D.Assign the attribute inside __init__ using self.
E.Assign the attribute in the class body, outside any methods.
AnswersA, E

Classmethods can modify class attributes via the cls parameter.

Why this answer

Option A is correct because a classmethod receives the class (cls) as its first argument, allowing you to assign or modify a class attribute via `cls.attribute = value`. This assignment affects the class itself, making the attribute shared among all instances, as the attribute is stored on the class object, not on instance dictionaries.

Exam trap

Python Institute often tests the distinction between class-level and instance-level attributes, and the trap here is that candidates confuse the @property decorator (which defines a computed instance property) with a class attribute, or think that a staticmethod can modify class state because it is defined inside the class body.

492
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

Standard base class for custom exceptions.

Why this answer

Option D is correct because 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.

493
MCQeasy

A developer writes a function that reads a configuration file and returns its contents as a string. The file might not exist. Which exception should be caught to handle a missing file?

A.FileNotFoundError
B.PermissionError
C.IOError
D.OSError
AnswerA

FileNotFoundError is specifically for missing files.

Why this answer

Option A is correct because `FileNotFoundError` is a built-in exception in Python that is raised when a file or directory is requested but does not exist. In Python 3, file-related I/O errors are organized under `OSError` with specific subclasses, and `FileNotFoundError` is the precise exception for a missing file, making it the most appropriate catch for this scenario.

Exam trap

Python Institute often tests the distinction between the broad `OSError` and its specific subclass `FileNotFoundError`, trapping candidates who think catching the parent class is safer, when in fact the exam expects precise exception handling for a missing file.

How to eliminate wrong answers

Option B is wrong because `PermissionError` is raised when the file exists but the process lacks the required permissions to access it, not when the file is missing. Option C is wrong because `IOError` was an alias for `OSError` in Python 2 but is no longer a separate exception in Python 3; catching it would not specifically target a missing file and is considered deprecated. Option D is wrong because `OSError` is the parent class for all system-related exceptions, including `FileNotFoundError`, but catching the parent is too broad and does not precisely handle the missing file case; it would also catch unrelated OS errors like permission or disk errors.

494
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

Option C is correct because 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.

495
MCQhard

Under CPython, what is the result of the following code? a = 'hello'; b = 'hello'; print(a is b)

A.True
B.False
C.NameError
D.None
AnswerA

String literals are often interned, so a and b reference the same object.

Why this answer

Due to string interning in CPython, string literals may be the same object. Thus a is b returns True. Option B is incorrect because interning often caches small strings.

496
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

Option A is correct because 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.

497
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

Correctly overrides __new__ and calls super to create the class.

Why this answer

Option D is correct because 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.

498
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

Option A is correct because 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.

499
Drag & Dropmedium

Drag and drop the steps to install a third-party package using pip in Python into the correct order.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

Installing a package with pip involves opening terminal, checking pip, using install command, optionally specifying version, and verifying.

500
MCQmedium

Which of the following best describes the immutability of strings in Python?

A.Strings can be modified in place using indexing.
B.Strings are mutable but require special methods.
C.Strings cannot be reassigned.
D.Strings cannot be changed after creation, but variables can be reassigned.
AnswerD

Correct: the string object itself is immutable, but the variable can point to a new string.

Why this answer

Option D is correct because strings in Python are immutable objects, meaning once a string is created, its contents cannot be changed. However, the variable referencing the string can be reassigned to point to a new string object. This distinction between mutability of the object and reassignment of the variable is fundamental to Python's data model.

Exam trap

Python Institute often tests the confusion between object mutability and variable reassignment, leading candidates to incorrectly believe that strings can be modified in place or that they cannot be reassigned at all.

How to eliminate wrong answers

Option A is wrong because strings do not support item assignment; attempting to modify a string via indexing (e.g., s[0] = 'a') raises a TypeError. Option B is wrong because strings are immutable, not mutable, and no special methods can change them in place; any operation that appears to modify a string actually creates a new string object. Option C is wrong because strings themselves can be reassigned to new variables or the same variable can be bound to a different string; the statement 'cannot be reassigned' confuses variable rebinding with object immutability.

501
Multi-Selectmedium

Which two methods can be used to remove leading whitespace from a string? (Choose two.)

Select 2 answers
A.s.strip()
B.s.lstrip()
C.s.split()
D.s.chomp()
E.s.rstrip()
AnswersA, B

strip() removes whitespace from both ends, effectively removing leading whitespace.

Why this answer

Both strip() (removes both ends) and lstrip() (removes only leading) remove leading whitespace. rstrip() removes trailing. split() and chomp() are not correct.

502
MCQeasy

A developer wants to ensure that a class attribute is shared across all instances. Which approach should be used?

A.Use the @property decorator.
B.Define the attribute inside a method without using self.
C.Define the attribute in the class body, outside any methods.
D.Define the attribute inside __init__ using self.
AnswerC

Class attributes are defined in the class body and shared by all instances.

Why this answer

Option C is correct because defining an attribute in the class body, outside any methods, creates a class attribute that is shared across all instances. Class attributes are stored in the class's __dict__ and are accessible via the class or any instance, unless shadowed by an instance attribute.

Exam trap

Python Institute often tests the distinction between class attributes and instance attributes, and the trap here is that candidates may confuse defining an attribute inside __init__ with creating a shared attribute, not realizing that __init__ always creates instance-specific attributes.

How to eliminate wrong answers

Option A is wrong because the @property decorator is used to define a method that can be accessed like an attribute, typically for computed or controlled access, not for creating a shared class attribute. Option B is wrong because defining an attribute inside a method without using self creates a local variable that is not accessible outside that method and does not become a class or instance attribute. Option D is wrong because defining the attribute inside __init__ using self creates an instance attribute, which is unique to each instance and not shared across all instances.

503
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

The slice [::-1] creates a reversed copy of the string.

Why this answer

Option B is correct because Python's slice notation `[::-1]` creates a reversed copy of the string by stepping through the sequence from end to start with a step of -1. Strings are immutable, so this returns a new string object with the characters in reverse order, exactly converting 'stressed' to 'desserts'.

Exam trap

Python Institute often tests the distinction between methods that modify in-place (like `list.reverse()`) and those that return a new object (like string slicing), trapping candidates who confuse list methods with string operations.

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.

504
MCQhard

Which of the following is true regarding Python's method resolution order (MRO) in multiple inheritance?

A.The MRO is computed using the C3 linearization algorithm, ensuring that each class appears before its parents and that monotonicity is preserved.
B.The MRO is always the same as the order of base classes specified in the class statement.
C.The MRO can be changed at runtime by modifying the __bases__ attribute of a class.
D.The MRO is determined by the order of base classes in the class definition, using a depth-first, left-to-right search without consideration of diamond inheritance.
AnswerA

C3 is correct.

Why this answer

Option A is correct because Python's method resolution order (MRO) is computed using the C3 linearization algorithm. This algorithm ensures that each class appears before its parents and that monotonicity is preserved, meaning the order of class precedence does not change when new subclasses are introduced. This is essential for resolving method calls in multiple inheritance scenarios, particularly with diamond inheritance.

Exam trap

The trap here is that candidates often assume the MRO follows a simple depth-first, left-to-right order (as in older Python versions or other languages), but Python's C3 algorithm can produce a different order to handle diamond inheritance correctly.

How to eliminate wrong answers

Option B is wrong because the MRO is not always the same as the order of base classes specified in the class statement; the C3 algorithm may reorder classes to satisfy monotonicity and local precedence order, especially in diamond inheritance. Option C is wrong because the MRO cannot be changed at runtime by modifying the __bases__ attribute; while __bases__ can be reassigned, the MRO is recalculated based on the new base classes using the C3 algorithm, but it is not directly mutable. Option D is wrong because the MRO is not determined by a simple depth-first, left-to-right search; Python explicitly abandoned that approach due to issues with diamond inheritance, and instead uses the C3 linearization algorithm to avoid inconsistent ordering.

505
Multi-Selecteasy

Which TWO of the following are valid ways to use string formatting in Python? (Choose two.)

Select 2 answers
A."Hello {0}".format("World")
B."Hello $s" % "World"
C.f"Hello {world}"
D."Hello %s" % "World"
E."Hello {name}".format("World")
AnswersA, D

Valid .format() method.

Why this answer

Old-style formatting with % and the .format() method are both valid and widely used. Option C uses $s which is invalid, D would raise KeyError, and E assumes a variable that may not be defined.

506
MCQmedium

A team is using inheritance but wants to prevent a method from being overridden in subclasses. What Python feature can enforce this?

A.Use a private method with double underscore prefix (__method).
B.Use a @final decorator.
C.Use @staticmethod.
D.Use @abstractmethod.
AnswerA

Name mangling makes the method harder to override accidentally, though it can still be overridden with the mangled name.

Why this answer

Option A is correct because in Python, prefixing a method name with double underscores (e.g., `__method`) triggers name mangling, which renames the method to `_ClassName__method` at compile time. This prevents subclasses from accidentally overriding the method, as the mangled name is unique to the class where it is defined, effectively making it private and non-overridable in subclasses.

Exam trap

Python Institute often tests the misconception that `@final` is a built-in Python decorator for preventing method overriding, but Python does not enforce `@final` at runtime, making the double underscore prefix the correct answer for runtime prevention.

How to eliminate wrong answers

Option B is wrong because Python does not have a built-in `@final` decorator; it is not a standard Python feature (though it exists in some third-party libraries or type checkers like `typing.final` in Python 3.8+, but it is not enforced at runtime by the interpreter). Option C is wrong because `@staticmethod` defines a method that does not receive an implicit first argument (self or cls), but it does not prevent overriding in subclasses; a subclass can still define a method with the same name. Option D is wrong because `@abstractmethod` is used to declare a method as abstract, requiring subclasses to override it, which is the opposite of preventing overriding.

507
Multi-Selecteasy

Which TWO of the following are correct ways to raise a custom exception in Python? (Assume CustomError and CustomException are user-defined.)

Select 2 answers
A.raise "Custom error"
B.raise 42
C.raise CustomError("invalid")
D.raise Exception
E.raise CustomException()
AnswersC, E

Valid: raises a custom exception instance.

Why this answer

Option C is correct because it raises a user-defined exception by instantiating the custom exception class `CustomError` with an argument (the string "invalid"). In Python, the `raise` statement must be followed by an exception instance or an exception class; `CustomError("invalid")` creates an instance of the custom exception, which is the proper way to raise a custom exception with a custom message.

Exam trap

Python Institute often tests the distinction between raising an exception class versus an exception instance, and the fact that only instances (or classes that are subclasses of `BaseException`) are valid arguments to `raise` — candidates mistakenly think any object can be raised or that raising a class without instantiation is the only correct way.

508
MCQmedium

A data scientist writes a script to parse a configuration file that contains lines in 'key=value' format. Some lines may have malformed data that cause a ValueError when trying to convert the value to an integer. The requirement is to process all valid lines and skip any that cause a ValueError, but continue processing subsequent lines. The script should log a warning for each skipped line, including the line number. Which implementation correctly fulfills this requirement? (Assume the file is opened with 'with open(...) as f'.)

A.Inside a for loop over f, wrap the parsing in a try-except ValueError block, log the error, and continue.
B.Wrap the entire file processing in a try-except ValueError block; if an error occurs, log and break.
C.Before parsing, check if the value string consists of digits using str.isdigit; if not, skip the line.
D.Inside a for loop over f, wrap the parsing in a try-except Exception block, log the error, and continue.
AnswerA

Specifically catches the expected error and continues processing.

Why this answer

Option A is correct because it uses a try-except ValueError block inside the for loop, which catches the specific exception when converting the value to an integer, logs a warning with the line number, and continues to the next line. This ensures all valid lines are processed while malformed lines are skipped without halting execution, fulfilling the requirement exactly.

Exam trap

Python Institute often tests the distinction between catching specific exceptions (ValueError) versus broad exceptions (Exception), and the trap here is that candidates may choose Option D thinking 'Exception' covers all errors, but it violates the principle of catching only what you can handle and may hide bugs.

How to eliminate wrong answers

Option B is wrong because wrapping the entire file processing in a try-except ValueError block will cause the loop to break on the first error, skipping all subsequent lines, which violates the requirement to continue processing. Option C is wrong because using str.isdigit() is unreliable for integer conversion—it returns False for negative numbers (e.g., '-5') or strings with leading zeros (e.g., '007'), causing valid lines to be incorrectly skipped. Option D is wrong because catching a broad 'Exception' instead of the specific 'ValueError' can mask unrelated errors (e.g., KeyError, TypeError) that should not be silently skipped, violating best practices for exception handling.

509
Multi-Selecthard

Which THREE of the following are valid ways to import a function named 'calculate' from a module named 'math_ops' located in a subpackage 'operations' of a package 'app'?

Select 3 answers
A.from app.operations.math_ops import calculate
B.import importlib; module = importlib.import_module('app.operations.math_ops'); module.calculate()
C.import app.operations.math_ops.calculate
D.from app.import operations.math_ops import calculate
E.import app.operations.math_ops; app.operations.math_ops.calculate()
AnswersA, B, E

Valid direct import of the function.

Why this answer

Option A is correct because it uses the standard Python import syntax to directly import the 'calculate' function from the 'math_ops' module, which is located in the 'operations' subpackage of the 'app' package. This is the most straightforward and recommended way to import a specific attribute from a module.

Exam trap

Python Institute often tests the distinction between importing a module versus importing an attribute from a module, and the trap here is that candidates mistakenly think 'import module.function' is valid syntax, when in fact only 'from module import function' or 'import module' (then using module.function) are correct.

510
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

Option B is correct because, 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 6

Page 7 of 7

All pages