Certified Associate Python Programmer PCAP (PCAP) — Questions 301375

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

Page 4

Page 5 of 7

Page 6
301
MCQeasy

Which of the following is a valid way to create an empty string in Python?

A.empty = str()
B.empty = ''
C.Both A and B
D.empty = ""
AnswerC

Both are valid ways to create an empty string.

Why this answer

Both `str()` and `''` (as well as `""`) are valid ways to create an empty string in Python. `str()` calls the built-in `str` constructor with no arguments, which returns an empty string object, while `''` and `""` are literal empty string syntax. Since all three produce the same immutable empty string object, option C is correct.

Exam trap

Python Institute often tests the distinction between `str()` and string literals, and the trap here is that candidates may think `str()` requires an argument or that only one of the literal forms is valid, when in fact both `''` and `""` are identical and `str()` without arguments returns an empty string.

How to eliminate wrong answers

Option A is wrong because it is actually a valid way to create an empty string, so it is not incorrect. Option B is wrong because it is also a valid way to create an empty string, so it is not incorrect. Option D is wrong because `""` is a valid empty string literal in Python, so it is not incorrect.

The only correct answer is C, which states that both A and B are valid.

302
MCQeasy

What is the result of the expression 'aBc'.lower()?

A.'abc'
B.'Abc'
C.'aBc'
D.'ABC'
AnswerA

All characters are converted to lowercase.

Why this answer

The `lower()` method returns a new string with all cased characters converted to lowercase. Since the original string 'aBc' contains an uppercase 'B', calling `.lower()` converts it to 'b', resulting in 'abc'. The method does not modify the original string but returns a new one.

Exam trap

Python Institute often tests whether candidates understand that `.lower()` does not modify the original string but returns a new one, and that it only affects uppercase letters, not other characters like digits or symbols.

How to eliminate wrong answers

Option B is wrong because 'Abc' would result from calling `.capitalize()` or `.title()`, not `.lower()`. Option C is wrong because it is the original string unchanged, but `.lower()` always returns a new string with all characters lowercased. Option D is wrong because 'ABC' would result from calling `.upper()`, not `.lower()`.

303
MCQmedium

A script uses `with open('data.bin', 'rb') as f:` to read binary data. Within the block, which method should be used to read exactly 4 bytes?

A.f.read(4)
B.f.seek(4)
C.f.readline()
D.f.read()
AnswerA

Reads up to 4 bytes.

Why this answer

The `read(n)` method reads exactly `n` bytes from the file object when the file is opened in binary mode (`'rb'`). Since the question specifies reading exactly 4 bytes, `f.read(4)` is the correct and direct approach. This method returns a bytes object of up to `n` bytes, but if the file has at least 4 bytes remaining, it will return exactly 4.

Exam trap

Python Institute often tests the distinction between `read()` (reads entire file), `read(n)` (reads exactly n bytes), and `seek()` (moves pointer without reading), and the trap here is that candidates may confuse `seek(4)` with reading 4 bytes, or assume `read()` without arguments reads a fixed number of bytes.

How to eliminate wrong answers

Option B is wrong because `f.seek(4)` moves the file pointer to byte offset 4 from the beginning, but does not read any data. Option C is wrong because `f.readline()` reads until a newline byte (`\n`) or EOF, which is not guaranteed to return exactly 4 bytes and is intended for text-based line reading, not fixed-size binary reads. Option D is wrong because `f.read()` with no argument reads the entire remaining contents of the file into memory, which will almost certainly not be exactly 4 bytes unless the file itself is exactly 4 bytes long.

304
MCQhard

A developer is working on a class hierarchy for geometric shapes. They have a base class Shape with an abstract method area(). They also have a mixin class Drawable that provides a method draw(). They want to create a class Rectangle that inherits from both Shape and Drawable. However, they encounter a TypeError when trying to instantiate Rectangle because the abstract method area() is not implemented. Which action should they take to resolve this?

A.Change the inheritance order to Drawable first, then Shape.
B.Implement the area() method in Rectangle.
C.Use a class decorator @abstractmethod for Rectangle.
D.Remove the abstract method from Shape by removing the @abstractmethod decorator.
AnswerB

All abstract methods must be implemented in a concrete subclass.

Why this answer

Option B is correct because the abstract method area() declared in the Shape base class must be implemented in any concrete subclass. In Python, a class that inherits from an ABC (Abstract Base Class) with an abstract method cannot be instantiated until that method is overridden. By providing an implementation of area() in Rectangle, the class becomes concrete and can be instantiated without raising a TypeError.

Exam trap

Python Institute often tests the misconception that changing inheritance order or using decorators can bypass the abstract method requirement, when in fact the only valid fix is to implement the abstract method in the concrete subclass.

How to eliminate wrong answers

Option A is wrong because changing the inheritance order does not affect the requirement to implement abstract methods; the TypeError arises from the missing implementation, not from the MRO. Option C is wrong because @abstractmethod is a decorator used to declare abstract methods, not a class decorator; applying it to Rectangle would make Rectangle itself abstract, not resolve the missing implementation. Option D is wrong because removing the @abstractmethod decorator from Shape would break the design contract, but more importantly, the question asks how to resolve the error while preserving the abstraction; removing the decorator eliminates the requirement but is not the intended solution for a proper class hierarchy.

305
Multi-Selectmedium

Which TWO of the following are true about the `__init__` method in Python?

Select 2 answers
A.It can be called manually.
B.It must return a value.
C.It can accept arguments.
D.It is not inherited.
E.It is called automatically when an instance is created.
AnswersC, E

Yes, arguments passed to the class are forwarded to `__init__` (except `self`).

Why this answer

Option C is correct because the `__init__` method can accept arguments, which are passed when creating an instance (e.g., `obj = MyClass(arg1, arg2)`). These arguments are forwarded to `__init__` by Python's instance creation machinery, allowing the method to initialize instance attributes with user-supplied values. This is a fundamental feature for parameterized object construction.

Exam trap

Python Institute often tests the misconception that `__init__` is the constructor or that it must return a value, when in fact `__new__` is the true constructor and `__init__` must return `None`.

306
MCQmedium

A programmer needs to replace every occurrence of 'cat' with 'dog' in a string s, but only if 'cat' is not preceded by 'big'. Which regex substitution would achieve this?

A.re.sub(r'bigcat', 'dog', s)
B.re.sub(r'cat', 'dog', s)
C.re.sub(r'(?<=big)cat', 'dog', s)
D.re.sub(r'(?<!big)cat', 'dog', s)
AnswerD

Uses negative lookbehind to ignore 'cat' when preceded by 'big'.

Why this answer

Option C uses negative lookbehind to exclude 'bigcat' from replacement. Option A replaces all 'cat'. Option B replaces 'bigcat'.

Option D replaces only 'cat' preceded by 'big'.

307
MCQmedium

What is the output of the following code? try: print(1/0) except: print('err') finally: print('fin')

A.fin err
B.fin
C.err fin
D.err
AnswerC

Exception triggers except, then finally runs.

Why this answer

Option C is correct because when a division by zero occurs, Python raises a ZeroDivisionError, which is caught by the bare except clause, printing 'err'. The finally clause always executes after the except block, printing 'fin'. Thus the output is 'err' followed by 'fin'.

Exam trap

Python Institute often tests the order of execution in try/except/finally blocks, specifically that the except block runs before the finally block when an exception is caught, and that the finally block always executes even if no exception occurs.

How to eliminate wrong answers

Option A is wrong because it shows 'fin err', implying the finally block runs before the except block, but in Python the except block runs first when an exception is caught. Option B is wrong because it shows only 'fin', ignoring that the except block prints 'err' when the exception is caught. Option D is wrong because it shows only 'err', omitting the finally block which always executes regardless of whether an exception occurs or is caught.

308
MCQeasy

What is the output of 'hello'.count('l')?

A.1
B.3
C.0
D.2
AnswerD

Correct, 'hello' contains two 'l' characters.

Why this answer

The string method `count('l')` returns the number of non-overlapping occurrences of the substring `'l'` in the string `'hello'`. The string `'hello'` contains the character `'l'` at indices 2 and 3, so the count is 2. Therefore, option D is correct.

Exam trap

Python Institute often tests the `count()` method with a single character substring to see if candidates correctly count occurrences, but the trap here is that some candidates might mistakenly count the total number of characters or misremember the string `'hello'` as having only one `'l'`.

How to eliminate wrong answers

Option A is wrong because it suggests only one `'l'` is present, but `'hello'` has two `'l'` characters. Option B is wrong because it counts three `'l'` characters, which would be true only for a string like `'lll'` or if the candidate mistakenly counts the `'l'` in `'hello'` three times. Option C is wrong because it indicates no `'l'` is found, which is incorrect as `'hello'` clearly contains two `'l'` characters.

309
MCQmedium

Which of the following demonstrates that strings are immutable?

A.s.upper() changes s in place
B.s[0] = 'J' results in a TypeError
C.s += '!' modifies s
D.s.replace('a','b') modifies s
AnswerB

Correct: strings are immutable, so item assignment is not allowed.

Why this answer

Option B is correct because attempting to assign a new character to an index of a string (e.g., s[0] = 'J') raises a TypeError, which directly demonstrates that strings are immutable in Python. Immutability means the object's value cannot be changed after creation; any operation that appears to modify a string actually creates a new string object.

Exam trap

Python Institute often tests the misconception that methods like upper(), replace(), or the += operator modify the original string in place, when in fact they always return a new string object, and the trap is that candidates confuse variable rebinding with in-place mutation.

How to eliminate wrong answers

Option A is wrong because s.upper() does not change s in place; it returns a new string with all uppercase characters, leaving the original string s unchanged. Option C is wrong because s += '!' does not modify the original string in place; it creates a new string object and rebinds the variable s to that new object, while the original string remains unchanged. Option D is wrong because s.replace('a','b') does not modify s; it returns a new string with the replacements applied, and the original string s is unaffected.

310
MCQhard

A developer defines a class 'A' with a method 'm' that uses 'self.a'. Class 'B' inherits from 'A' and defines __init__ that sets 'self.a = 10'. An instance of B is created and method m is called. What is the output?

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

B's __init__ sets a to 10.

Why this answer

Option C is correct because when an instance of class B is created, its __init__ method sets self.a = 10. When method m (inherited from A) is called on that instance, self refers to the B instance, so self.a resolves to 10. Python's attribute lookup follows the instance's __dict__ first, finding the attribute set by B's __init__.

Exam trap

Python Institute often tests the misconception that inherited methods use the parent class's attribute values rather than the instance's own attributes, leading candidates to incorrectly expect an AttributeError or None.

How to eliminate wrong answers

Option A is wrong because self.a is not None; it is explicitly set to 10 in B.__init__, so the output is not None. Option B is wrong because there is no AttributeError; the attribute a exists on the instance due to B.__init__, so the lookup succeeds. Option D is wrong because self.a is not 0; it is assigned the integer 10, not a default or zero value.

311
MCQhard

A package 'pkg' is installed as an egg-link in development mode. Inside the package, there is a module 'submod.py' that uses relative imports. When a developer modifies 'submod.py', they find that changes are not always reflected on import. What is the most likely reason?

A.The sys.path is altered by the egg-link, causing a different module to be loaded.
B.Relative imports are cached in the __init__.py file.
C.Python's module caching in sys.modules prevents re-loading the modified source.
D.The __pycache__ directory is not cleared automatically.
AnswerC

When using egg-link, the module is loaded once; subsequent imports use cached version unless explicitly reloaded.

Why this answer

Option C is correct because Python caches imported modules in `sys.modules`. When a module is imported, Python stores the module object in `sys.modules` and subsequent imports retrieve it from this cache without re-executing the module's code. Modifying the source file of `submod.py` does not automatically invalidate this cache, so the changes are not reflected unless the module is explicitly reloaded (e.g., with `importlib.reload()`) or the interpreter is restarted.

Exam trap

Python Institute often tests the distinction between source file modification and module caching, where candidates mistakenly think the issue is with bytecode caching (`__pycache__`) or path resolution, rather than the `sys.modules` cache that prevents re-execution of the module's code.

How to eliminate wrong answers

Option A is wrong because an egg-link installs a development mode package by adding a path to `sys.path` that points to the source directory; it does not cause a different module to be loaded—the same source file is used, but the caching issue still applies. Option B is wrong because relative imports are not cached in `__init__.py`; they are resolved at import time based on the package's `__name__` and `__path__`, and caching occurs in `sys.modules`, not in `__init__.py`. Option D is wrong because `__pycache__` stores bytecode files (`.pyc`) for performance, but Python checks the modification time of the source file against the cached bytecode; if the source is newer, it recompiles—so the issue is not about clearing `__pycache__` but about the module object already being in `sys.modules`.

312
Multi-Selecteasy

Which TWO of the following are valid uses for the '__name__' variable in a Python module?

Select 2 answers
A.To get the file path of the module.
B.To control which names are exported when using 'from module import *'.
C.To determine which module imported it.
D.To check if the module is being run as the main program.
E.To get the fully qualified name of the module (e.g., 'package.module').
AnswersD, E

If __name__ == '__main__', it's the entry point.

Why this answer

Option D is correct because the '__name__' variable is set to the string '__main__' when the module is executed directly as the main program (e.g., via 'python module.py'). This allows a module to include code that runs only when it is the entry point, not when it is imported by another module. The check is typically done with 'if __name__ == "__main__":'.

Exam trap

The trap here is that candidates often confuse '__name__' with '__file__' (for file paths) or '__all__' (for export control), and may incorrectly think '__name__' can identify the importing module, which Python does not directly support.

313
Multi-Selectmedium

Which TWO statements about the sys module are true?

Select 2 answers
A.sys.path is a tuple of module search paths.
B.sys.modules is a list of all loaded modules.
C.sys.exit() raises SystemExit with a default exit code of 0.
D.The sys module is automatically imported in every Python script.
E.sys.argv[0] is the script name.
AnswersC, E

sys.exit() raises SystemExit(0) to terminate the program.

Why this answer

Option C is correct because `sys.exit()` raises the `SystemExit` exception, and when called without an argument, the default exit code is 0, indicating successful termination. This behavior is defined in the Python documentation for the `sys` module.

Exam trap

Python Institute often tests the distinction between mutable and immutable types (list vs. tuple) and between data structures (list vs. dict) for `sys.path` and `sys.modules`, as well as the fact that `sys` is not a built-in module that is auto-imported.

314
MCQmedium

What is the result of 'Python'.find('th')?

A.1
B.-1
C.2
D.0
AnswerC

'th' starts at index 2.

Why this answer

The string method `find()` returns the lowest index where the substring is found. In 'Python', the substring 'th' starts at index 2 (P=0, y=1, t=2, h=3, o=4, n=5). Therefore, the result is 2, making option C correct.

Exam trap

Python Institute often tests the zero-based indexing of strings, leading candidates to mistakenly count from 1 instead of 0, or to confuse `find()` with `index()` and expect an exception for missing substrings.

How to eliminate wrong answers

Option A is wrong because 1 would be the index of 'y', not the start of 'th'. Option B is wrong because -1 is returned only when the substring is not found, but 'th' is present in 'Python'. Option D is wrong because 0 would be the index of 'P', not the start of 'th'.

315
MCQeasy

A developer writes a function that reads a file and processes its content. The function should handle the case where the file does not exist without catching other I/O errors. Which exception should be caught?

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

FileNotFoundError is the specific exception for a missing file, ideal for this scenario.

Why this answer

Option D is correct because `FileNotFoundError` is a specific subclass of `OSError` that is raised exactly when a file or directory is requested but does not exist. By catching only `FileNotFoundError`, the function handles the missing-file scenario without masking other I/O errors such as permission issues or disk failures, which is the precise requirement stated in the question.

Exam trap

Python Institute often tests the Python exception hierarchy, and the trap here is that candidates mistakenly choose `IOError` or `OSError` because they are broader and seem 'safer,' but the question explicitly requires handling only the missing-file case without catching other I/O errors.

How to eliminate wrong answers

Option A is wrong because `PermissionError` is raised when the file exists but the process lacks the necessary permissions (e.g., read or write access), not when the file is missing. Option B is wrong because `IOError` is an alias for `OSError` in Python 3 and is too broad; catching it would also catch unrelated I/O errors like permission or disk errors, violating the requirement to avoid catching other I/O errors. Option C is wrong because `OSError` is the parent class for many file-related exceptions (including `FileNotFoundError`, `PermissionError`, etc.); catching it would handle all OS-level errors, not just the missing-file case.

316
MCQhard

When a class defines both __getattr__ and __getattribute__, which one is called when accessing an attribute that exists in the instance?

A.__getattr__ always overrides __getattribute__.
B.Both __getattr__ and __getattribute__ are called, in that order.
C.Only __getattr__ is called.
D.__getattribute__ is called, and __getattr__ is not called.
AnswerD

For existing attributes, __getattribute__ returns the value directly.

Why this answer

In Python, when both __getattr__ and __getattribute__ are defined in a class, __getattribute__ is always called first for every attribute access. If the attribute exists in the instance (e.g., in the instance dictionary or via a descriptor), __getattribute__ returns it directly, and __getattr__ is never invoked. __getattr__ is only called as a fallback when __getattribute__ raises an AttributeError. Therefore, for an existing attribute, only __getattribute__ runs, making option D correct.

Exam trap

Python Institute often tests the misconception that __getattr__ is the primary hook for attribute access, when in fact __getattribute__ is always called first and __getattr__ is only a fallback for missing attributes.

How to eliminate wrong answers

Option A is wrong because __getattr__ does not override __getattribute__; rather, __getattribute__ takes precedence for all accesses, and __getattr__ is only a fallback for missing attributes. Option B is wrong because both methods are not called in order for an existing attribute; __getattribute__ returns the value immediately, so __getattr__ is not invoked at all. Option C is wrong because __getattr__ is not called when the attribute exists; it is only triggered when __getattribute__ raises an AttributeError.

317
MCQmedium

A developer installs a third-party package using pip, but when they try to import it in their script, Python raises a ModuleNotFoundError. The package is definitely installed (pip list shows it). What is the most likely cause?

A.The Python interpreter being used is different from the one where the package was installed.
B.The package name contains a hyphen.
C.The script is in a directory that shadows the package name.
D.The package does not have an __init__.py file.
AnswerA

Common issue when multiple Python versions or virtual environments exist.

Why this answer

When a package is installed via pip, it is placed into the site-packages directory of a specific Python interpreter. If the developer runs their script with a different Python interpreter (e.g., one from a virtual environment, a different version, or a system Python vs. a user-installed Python), that interpreter's import system will not search the site-packages where the package was installed, resulting in a ModuleNotFoundError even though pip list shows the package. This is the most common cause of such a mismatch.

Exam trap

Python Institute often tests the misconception that a package name with a hyphen is invalid for import, leading candidates to choose option B, but the real issue is interpreter mismatch, which is the most common and subtle cause of ModuleNotFoundError in multi-interpreter environments.

How to eliminate wrong answers

Option B is wrong because Python's import system automatically converts hyphens in package names to underscores (e.g., pip install my-package allows import my_package), so a hyphen in the package name does not cause a ModuleNotFoundError. Option C is wrong because a script shadowing a package name would cause an ImportError or unexpected behavior only if the script's directory contains a module or package with the same name as the imported package, but it would not produce a ModuleNotFoundError; the error would be a different one (e.g., AttributeError or incorrect import). Option D is wrong because __init__.py is only required for regular packages in Python 3.3+ for namespace packages or for packages that need initialization code; third-party packages installed via pip are typically regular packages or namespace packages that work without __init__.py, and its absence does not cause a ModuleNotFoundError.

318
MCQeasy

A class MyClass defines __str__ and __repr__ methods. What is the purpose of __repr__?

A.To return a human-readable string for end users
B.To compare object equality
C.To return a hash value of the object
D.To return an unambiguous representation of the object, ideally for debugging
AnswerD

__repr__ should be unambiguous and, if possible, a valid Python expression.

Why this answer

The `__repr__` method is designed to return an unambiguous string representation of an object, ideally one that can be used to recreate the object or that clearly shows its internal state for debugging purposes. This is distinct from `__str__`, which targets end-user readability. The Python documentation explicitly states that `__repr__` should be unambiguous, while `__str__` should be readable.

Exam trap

The trap here is that candidates confuse `__repr__` with `__str__`, assuming both serve the same purpose, but Cisco specifically tests that `__repr__` is for unambiguous debugging output, not user-friendly display.

How to eliminate wrong answers

Option A is wrong because returning a human-readable string for end users is the purpose of `__str__`, not `__repr__`. Option B is wrong because comparing object equality is handled by the `__eq__` method, not `__repr__`. Option C is wrong because returning a hash value is the job of the `__hash__` method, which is used for dictionary keys and set membership, not `__repr__`.

319
MCQhard

A developer runs 'pip install mypackage' but gets a 'PermissionError'. Which command should be used to install the package for the current user only?

A.sudo pip install mypackage
B.pip install --user mypackage
C.pip install --ignore-installed mypackage
D.pip install --target mypackage
AnswerB

Correct. This installs the package for the current user only, no root required.

Why this answer

Option B is correct because the `--user` flag instructs pip to install the package into the user's site-packages directory (e.g., `~/.local/lib/pythonX.Y/site-packages` on Unix), which does not require elevated permissions. This avoids the `PermissionError` that occurs when pip tries to write to the system-wide site-packages directory (e.g., `/usr/lib/python3/dist-packages`) without administrator privileges.

Exam trap

Python Institute often tests the misconception that `sudo` is the correct way to fix permission errors in pip, but the exam expects candidates to know the safer, user-scoped `--user` flag as the proper solution for installing packages without administrative rights.

How to eliminate wrong answers

Option A is wrong because `sudo pip install mypackage` runs pip with superuser privileges, which bypasses the permission error but is strongly discouraged as it can corrupt the system Python environment and bypass security checks. Option C is wrong because `--ignore-installed` tells pip to ignore already installed packages and reinstall, but it does not change the installation target directory, so the permission error would still occur. Option D is wrong because `--target mypackage` specifies a custom installation directory (e.g., `./mypackage`) but does not resolve the underlying permission issue; it would still fail if the target directory is not writable or is misused as a package name.

320
Drag & Dropmedium

Drag and drop the steps to debug a Python script using pdb 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

Debugging with pdb involves setting a trace, running the script, using commands to step through code, setting breakpoints, and exiting.

321
MCQeasy

A developer wants to implement a read-only property for a class 'Temperature' that returns the temperature in Celsius but prevents external modification. Which code snippet correctly defines such a property?

A.class Temperature: @property def celsius(self): return self._celsius @celsius.setter def celsius(self, val): self._celsius = val
B.class Temperature: def __setattr__(self, name, val): if name == 'celsius': raise AttributeError
C.class Temperature: @property def celsius(self): return self._celsius
D.class Temperature: def __init__(self, c): self.celsius = c
AnswerC

This defines a getter only, making the property read-only.

Why this answer

Option C is correct because it defines a read-only property using the `@property` decorator with only a getter method. Without a setter, any attempt to assign a value to `celsius` will raise an `AttributeError`, making the property read-only. This is the standard Pythonic way to implement a read-only attribute.

Exam trap

Python Institute often tests the misconception that a property without a setter is still writable by default, or that overriding `__setattr__` is a valid alternative to `@property` for creating a read-only attribute, but the correct approach is to omit the setter decorator entirely.

How to eliminate wrong answers

Option A is wrong because it includes a setter method (`@celsius.setter`), which allows external modification of the property, contradicting the requirement for a read-only property. Option B is wrong because overriding `__setattr__` to raise an `AttributeError` for the name 'celsius' would prevent setting the attribute even inside the class (e.g., in `__init__`), breaking normal initialization and not providing a proper property interface. Option D is wrong because it simply assigns `celsius` as a regular instance attribute in `__init__`, which is fully writable and does not use the `@property` decorator, so it is not a read-only property.

322
MCQmedium

A team is developing a system that must handle different types of documents (PDF, Word, etc.). Each document type has a unique parsing method. To avoid massive conditional logic, which OOP concept should be applied?

A.Polymorphism
B.Encapsulation
C.Inheritance
D.Abstraction
AnswerA

Polymorphism enables each subclass to provide its own implementation of a common interface.

Why this answer

Polymorphism allows different document types (PDF, Word, etc.) to be treated uniformly through a common interface (e.g., a `parse()` method) while each class implements its own parsing logic. This eliminates the need for conditional statements (like `if type == 'PDF'`) because the correct method is resolved at runtime via dynamic dispatch, which is exactly what the team needs to avoid massive conditional logic.

Exam trap

Python Institute often tests the distinction between inheritance and polymorphism: candidates mistakenly think inheritance alone solves the problem, but without polymorphic method dispatch, you still need conditional logic to handle different types.

How to eliminate wrong answers

Option B (Encapsulation) is wrong because encapsulation focuses on bundling data and methods together and restricting direct access to internal state (e.g., via private attributes), not on avoiding conditional logic for different types. Option C (Inheritance) is wrong because while inheritance can share common code among document types, it does not by itself eliminate the need for conditionals; you would still need to check the object's type to call the correct parsing method without polymorphism. Option D (Abstraction) is wrong because abstraction hides implementation details behind an interface or abstract class, but without polymorphism you would still need conditional logic to decide which concrete implementation to invoke.

323
MCQmedium

Refer to the exhibit. Which of the following correctly shows the MRO of class D?

A.[D, B, C, A, object]
B.[D, A, B, C, object]
C.[D, B, A, C, object]
D.[D, C, B, A, object]
AnswerA

Correct MRO.

Why this answer

Option A is correct because Python's Method Resolution Order (MRO) for class D, which inherits from B and C (where B inherits from A and C inherits from A), follows the C3 linearization algorithm. The MRO is computed as D -> B -> C -> A -> object, ensuring that each class appears before its parents and that the order respects the local precedence order of D's bases (B before C).

Exam trap

Python Institute often tests the C3 linearization rule that the local precedence order (the order of bases in the class definition) must be preserved, so candidates mistakenly reorder bases based on inheritance depth rather than the explicit left-to-right order in the class statement.

How to eliminate wrong answers

Option B is wrong because it places A before B and C, violating the local precedence order of D's bases (B, C) and the C3 algorithm's requirement that a parent class appears after all its subclasses. Option C is wrong because it places A before C, which breaks the monotonicity of the C3 linearization; since C inherits from A, A must come after C. Option D is wrong because it places C before B, ignoring the explicit order of bases in class D's definition (B then C), which the C3 algorithm respects as the local precedence order.

324
MCQeasy

A user entered a string ' Hello, World! '. Which expression returns 'Hello, World!'?

A.s.split()
B.s.strip()
C.s.rstrip()
D.s.lstrip()
AnswerB

strip() removes whitespace from both ends.

Why this answer

The `strip()` method removes all leading and trailing whitespace characters from a string, returning a new string without the surrounding spaces. In this case, `s.strip()` removes the three leading spaces and three trailing spaces from ' Hello, World! ', resulting in 'Hello, World!'.

Exam trap

Python Institute often tests the distinction between `strip()`, `lstrip()`, and `rstrip()` by presenting a string with both leading and trailing whitespace, tempting candidates to choose a partial removal method when only the full `strip()` works.

How to eliminate wrong answers

Option A is wrong because `split()` without arguments splits the string on any whitespace and returns a list of substrings, not a single string; it would produce ['Hello,', 'World!'] (or similar depending on whitespace). Option C is wrong because `rstrip()` only removes trailing whitespace, leaving the leading spaces intact, so it would return ' Hello, World!'. Option D is wrong because `lstrip()` only removes leading whitespace, leaving the trailing spaces intact, so it would return 'Hello, World! '.

325
Multi-Selecthard

Which TWO statements about Python's name mangling are correct?

Select 2 answers
A.Name mangling applies to all method names that start with a single underscore.
B.The mangled name format is _ClassName__attribute.
C.Name mangling prevents external code from accessing the attribute entirely.
D.Name mangling is applied to attributes that start with two underscores but do not end with two underscores.
E.Name mangling occurs at runtime.
AnswersB, D

Correct.

Why this answer

Option B is correct because Python's name mangling transforms an attribute name like `__attribute` defined in a class `MyClass` into `_MyClass__attribute`. This mechanism is specifically designed to avoid name clashes in subclasses, not to enforce privacy. The transformation is done by the compiler at definition time, not at runtime.

Exam trap

Python Institute often tests the misconception that name mangling provides true access control (like private in Java), when in fact it is only a name transformation that can be bypassed by using the mangled name directly.

326
Multi-Selecthard

Which THREE methods return a boolean value?

Select 3 answers
A.str.upper()
B.str.startswith()
C.str.islower()
D.str.isalpha()
E.str.find()
AnswersB, C, D

Returns True or False.

Why this answer

B is correct because str.startswith() returns True if the string starts with the specified prefix, otherwise False. It is a boolean-returning method, as required by the question.

Exam trap

Python Institute often tests the distinction between methods that return a boolean versus those that return a new string or an integer, leading candidates to mistakenly select str.upper() or str.find() because they think any method that checks a condition returns a boolean.

327
MCQmedium

A package 'tools' has the structure: tools/__init__.py, tools/calc.py, tools/io.py. In __init__.py, the developer writes: from . import calc. A user tries: import tools; print(tools.add(1,2)). This fails with AttributeError. Why?

A.The add function is not imported into the tools package namespace.
B.The function add is not defined in calc.py.
C.Relative imports are not allowed in __init__.py files.
D.The user should use tools.calc.add instead.
AnswerA

The __init__.py imports the calc module, not its functions.

Why this answer

Option A is correct because the `__init__.py` file only imports the `calc` module itself into the `tools` package namespace, not the `add` function. When a user calls `tools.add(1,2)`, Python looks for `add` directly in the `tools` namespace, but it is not there — it is only accessible as `tools.calc.add`. The `from . import calc` statement binds the name `calc` to the module, not its contents.

Exam trap

Python Institute often tests the misconception that importing a submodule automatically makes its contents available at the package level, when in fact only the submodule name is added to the package namespace.

How to eliminate wrong answers

Option B is wrong because the question does not state that `add` is undefined in `calc.py`; the error is about namespace visibility, not definition. Option C is wrong because relative imports like `from . import calc` are perfectly allowed in `__init__.py` files — they are the standard way to expose submodules. Option D is wrong because while `tools.calc.add` would work, the question asks why the original call fails, not how to fix it; the failure is due to the missing import of `add` into the package namespace.

328
MCQmedium

A developer wants to ensure that a file is always closed after writing, even if an exception occurs. Which approach is considered best practice in Python?

A.Use try/finally with explicit f.close()
B.Rely on the garbage collector to close the file
C.Use try/except/finally with f.close() in both except and finally
D.Use the with statement: with open('file.txt', 'w') as f: ...
AnswerD

Context manager ensures automatic cleanup.

Why this answer

Option D is correct because the `with` statement in Python implements a context manager that automatically calls the file's `__exit__` method, which closes the file even if an exception occurs inside the block. This is the idiomatic and recommended approach for resource management, as it guarantees cleanup without requiring explicit `close()` calls.

Exam trap

Python Institute often tests the misconception that `try/finally` with explicit `close()` is equivalent to the `with` statement, but the trap is that the `with` statement is the explicitly recommended best practice in the Python documentation and PEP 343, making it the correct answer over more manual approaches.

How to eliminate wrong answers

Option A is wrong because while `try/finally` with explicit `f.close()` does ensure the file is closed, it is more verbose and error-prone than the `with` statement, and it is not considered best practice in modern Python. Option B is wrong because relying on the garbage collector to close the file is unreliable — the garbage collector may not run immediately, and file descriptors are a limited OS resource that should be released deterministically. Option C is wrong because placing `f.close()` in both `except` and `finally` is redundant and unnecessary; the `finally` block alone guarantees execution regardless of exceptions, so duplicating the call in `except` adds no benefit and can lead to double-close errors if not handled carefully.

329
MCQmedium

A developer is working on a logging system where dynamic values are inserted into a template string. The template is 'User %s logged in at %s'. The developer has the username and timestamp as separate variables. Which approach is most Pythonic (PEP 498) and recommended for new code?

A.Use %-formatting: 'User %s logged in at %s' % (username, timestamp)
B.Use .format(): 'User {} logged in at {}'.format(username, timestamp)
C.Concatenate: 'User ' + username + ' logged in at ' + timestamp
D.Use an f-string: f'User {username} logged in at {timestamp}'
AnswerD

f-strings are the recommended approach for string formatting in Python 3.6+.

Why this answer

Option C (f-string) is the most Pythonic and recommended for new code per PEP 498. Option A (% formatting) is older. Option B (.format()) is also fine but f-strings are often preferred for readability when variables are available.

Option D (concatenation) is prone to errors and less readable.

330
MCQhard

A Python class 'Shape' defines an abstract method 'area'. Subclasses 'Circle' and 'Square' implement 'area'. A function 'calculate_area(shape)' expects a 'Shape' instance. Which principle ensures that the function works correctly without knowing the specific subclass?

A.Interface Segregation Principle
B.Liskov Substitution Principle
C.Single Responsibility Principle
D.Dependency Inversion Principle
AnswerB

LSP ensures that any subclass can replace the base class without breaking the function.

Why this answer

The Liskov Substitution Principle (LSP) states that objects of a superclass should be replaceable with objects of its subclasses without affecting the correctness of the program. In this scenario, 'calculate_area(shape)' accepts a 'Shape' instance, and because both 'Circle' and 'Square' are proper subtypes that honor the contract of the 'area' method, the function works correctly regardless of which subclass is passed. This is the core of LSP: substitutability without side effects.

Exam trap

Python Institute often tests LSP by presenting a scenario where a subclass overrides a method in a way that changes the expected behavior (e.g., raising an exception or returning a different type), and candidates mistakenly choose Interface Segregation or Dependency Inversion because they confuse 'substitutability' with 'abstraction' or 'interface design'.

How to eliminate wrong answers

Option A is wrong because the Interface Segregation Principle (ISP) focuses on splitting large interfaces into smaller, specific ones so that clients only depend on methods they use; it does not address the substitutability of subclasses in a function parameter. Option C is wrong because the Single Responsibility Principle (SRP) dictates that a class should have only one reason to change, which is unrelated to polymorphic behavior across subclasses. Option D is wrong because the Dependency Inversion Principle (DIP) deals with depending on abstractions rather than concretions, but it does not specifically ensure that a subclass can be used in place of its parent class without breaking functionality—that is LSP's role.

331
MCQeasy

A developer defines a class with a private attribute `_value` and wants to provide controlled access. Which approach is the most Pythonic?

A.Use `__slots__` to restrict attribute creation.
B.Make `_value` public and rely on documentation.
C.Use @property to define getter and setter methods.
D.Define `get_value()` and `set_value()` methods.
AnswerC

Property decorators provide controlled access in a Pythonic way.

Why this answer

Option C is correct because using the `@property` decorator is the most Pythonic way to implement controlled access to a private attribute. It allows you to define getter and setter methods that can be called like regular attribute access (e.g., `obj.value`), preserving encapsulation while maintaining a clean, non-method-call interface. This approach aligns with Python's philosophy of 'we are all consenting adults' and avoids the verbosity of explicit getter/setter methods.

Exam trap

Python Institute often tests the distinction between Pythonic idioms and patterns borrowed from other languages (like Java), so the trap here is that candidates familiar with Java or C++ may choose Option D (explicit getter/setter methods) because it looks familiar, missing that Python's `@property` is the preferred, more concise approach.

How to eliminate wrong answers

Option A is wrong because `__slots__` is used to restrict the attributes that can be assigned to an instance, not to provide controlled access to a specific attribute; it does not define getters or setters. Option B is wrong because making `_value` public and relying on documentation violates encapsulation principles and provides no runtime enforcement or validation, which is not Pythonic for controlled access. Option D is wrong because defining `get_value()` and `set_value()` methods is a Java-style approach that is considered non-Pythonic; Python prefers the `@property` decorator for a more natural attribute-like syntax.

332
MCQmedium

Refer to the exhibit. What is the output?

A.12.56 0
B.Error
C.0 0
D.0 12.56
AnswerD

Correct.

Why this answer

First object is Shape, area returns 0. Second is Circle, area returns 3.14*4=12.56.

333
Multi-Selecthard

Which THREE of the following are characteristics of Python's special methods (dunder methods)? (Select exactly three.)

Select 3 answers
A.They enable operator overloading for user-defined classes.
B.They can be defined in a class to customize behavior.
C.Every class automatically has all special methods predefined.
D.They must be defined inside the class definition and cannot be added later.
E.They are automatically invoked by Python in certain contexts.
AnswersA, B, E

E.g., __add__ for +.

Why this answer

Option A is correct because special methods like `__add__` and `__eq__` allow user-defined classes to redefine the behavior of operators such as `+` and `==`. When Python encounters an operator expression, it looks up the corresponding dunder method on the object's class, enabling operator overloading in a clean, syntactic way.

Exam trap

Python Institute often tests the misconception that all dunder methods are automatically inherited or that they cannot be added dynamically, so candidates mistakenly select option C or D without realizing that Python's data model only provides defaults for a minimal set and allows runtime assignment to classes.

334
MCQmedium

When processing a large text file, a developer notices that using str.replace() in a loop is slow. Which alternative is most efficient for multiple replacements?

A.Use str.maketrans() on the original string
B.Use re.sub() from the re module
C.Use str.translate() with a translation table
D.Chain multiple str.replace() calls
AnswerC

str.translate() performs all replacements in a single pass.

Why this answer

Option C is correct because `str.translate()` with a translation table built by `str.maketrans()` performs all character replacements in a single pass over the string, operating at the C level in CPython. This avoids the O(n) per-replacement overhead of `str.replace()` in a loop, making it the most efficient choice for multiple, fixed-character substitutions on large text.

Exam trap

Python Institute often tests the misconception that `str.maketrans()` alone performs replacements, when in fact it only generates the table required by `str.translate()`, leading candidates to mistakenly select option A.

How to eliminate wrong answers

Option A is wrong because `str.maketrans()` only creates a translation table; it does not perform any replacement itself and must be used with `str.translate()` to be effective. Option B is wrong because `re.sub()` uses a regex engine that compiles patterns and backtracks, incurring significant overhead for simple, fixed-character replacements compared to a direct translation table. Option D is wrong because chaining multiple `str.replace()` calls processes the entire string multiple times (once per call), leading to O(n*m) complexity where m is the number of replacements, which is inefficient for large files.

335
MCQhard

A developer writes: s = 'abc'; s[0] = 'x'. What happens?

A.s becomes 'xbc'
B.TypeError: 'str' object does not support item assignment
C.ValueError: string index out of range
D.s becomes 'abc' and no error
AnswerB

This is the exact error raised.

Why this answer

In Python, strings are immutable, meaning their contents cannot be changed after creation. Attempting to assign a new character to an index position (e.g., `s[0] = 'x'`) raises a `TypeError: 'str' object does not support item assignment`. This is a fundamental property of the `str` type in Python, enforced at the interpreter level.

Exam trap

Python Institute often tests the immutability of strings by presenting an assignment to an index, tricking candidates who confuse strings with mutable sequences like lists.

How to eliminate wrong answers

Option A is wrong because it assumes strings are mutable like lists, but Python strings are immutable and cannot be modified in-place. Option C is wrong because the index 0 is valid for a string of length 3, so no `IndexError` or `ValueError` occurs; the error is about assignment, not indexing. Option D is wrong because Python does not silently ignore invalid assignments; it raises an exception immediately.

336
Drag & Dropmedium

Drag and drop the steps to create a simple HTTP server using the http.server module 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

Creating an HTTP server involves importing http.server, defining a handler, overriding methods, creating an HTTPServer instance, and calling serve_forever().

337
Multi-Selecthard

Which THREE of the following are valid ways to create a string in Python?

Select 3 answers
A.'Hello'
B.'Hello'
C.f'{name}'
D.`Hello`
E.'''Hello'''
AnswersB, C, E

Single quotes are valid string delimiters.

Why this answer

Option B is correct because single quotes are a standard string literal delimiter in Python, as defined in the Python language reference. The expression 'Hello' creates a string object with the value 'Hello'.

Exam trap

Python Institute often tests the distinction between valid Python string delimiters and those from other languages, such as backticks, to catch candidates who confuse Python syntax with JavaScript or shell scripting.

338
MCQeasy

Which of the following expressions returns the string 'Hello' repeated three times?

A.'Hello' * 3
B.'Hello' + 3
C.'Hello' * '3'
D.'Hello' * 3.0
AnswerA

Repeats the string three times: 'HelloHelloHello'.

Why this answer

In Python, the multiplication operator (*) when used with a string and an integer performs string repetition. 'Hello' * 3 returns the string 'HelloHelloHello' by concatenating three copies of the original string. This is a core feature of Python's sequence protocol, where strings are sequences of characters.

Exam trap

The trap here is that candidates may think the + operator can coerce types or that string multiplication accepts any numeric type, but Python strictly requires an integer for the repetition count and raises a TypeError for floats or strings.

How to eliminate wrong answers

Option B is wrong because the + operator cannot concatenate a string with an integer; it raises a TypeError: can only concatenate str (not 'int') to str. Option C is wrong because '3' is a string, not an integer; multiplying a string by a string raises a TypeError: can't multiply sequence by non-int of type 'str'. Option D is wrong because 3.0 is a float, not an integer; multiplying a string by a float raises a TypeError: can't multiply sequence by non-int of type 'float'.

339
MCQeasy

Which mode should be used when opening a file for writing such that new content is appended to the end without truncating existing content?

A.'x'
B.'r+'
C.'w'
D.'a'
AnswerD

Correct: append mode.

Why this answer

Option D ('a') is correct because the 'a' mode opens a file for appending, which means new data is written to the end of the file without truncating any existing content. This is the standard behavior defined in Python's open() function for append mode.

Exam trap

Python Institute often tests the confusion between 'w' (which truncates) and 'a' (which appends), and candidates mistakenly choose 'w' thinking it simply writes without realizing it destroys existing data.

How to eliminate wrong answers

Option A ('x') is wrong because 'x' is exclusive creation mode — it opens a file for writing but fails if the file already exists, and it does not append. Option B ('r+') is wrong because 'r+' opens a file for both reading and writing, but it does not automatically position the write pointer at the end; it starts at the beginning and can overwrite existing content. Option C ('w') is wrong because 'w' opens a file for writing and truncates the file to zero length, destroying all existing content.

340
MCQeasy

Which expression returns the last character of string s?

A.s[-1]
B.s[len(s)]
C.s[-0]
D.s[0]
AnswerA

Correct: Negative index -1 refers to the last element.

Why this answer

In Python, negative indices count from the end. s[-1] accesses the last character. s[len(s)] raises IndexError, s[0] gets the first character, and s[-0] is equivalent to s[0].

341
Matchingmedium

Match each list method to its effect.

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

Concepts
Matches

Adds x to end

Appends elements from iterable

Inserts x at index i

Removes first occurrence of x

Removes and returns last item

Why these pairings

Common list methods.

342
Multi-Selecthard

Which THREE of the following escape sequences are valid in a Python string and represent a single character? (Select exactly three.)

Select 3 answers
A.\x
B.\q
C.\'
D.\\
E.\n
AnswersC, D, E

Single quote escape.

Why this answer

Option B (\'), Option C (\\), and Option E (\n) are valid escape sequences. Option A (\q) is not a standard escape sequence. Option D (\x) is invalid without two hex digits; \x1F is valid.

343
MCQmedium

A Python application needs to load a configuration file that should be placed in the same directory as the main script. The developer uses the __file__ attribute to get the script's path. Which expression correctly obtains the directory containing the main script?

A.os.path.dirname(os.path.realpath(__file__))
B.os.path.dirname(os.path.abspath(__file__))
C.os.getcwd()
D.os.path.abspath(__file__)
AnswerB

Correctly gets the absolute directory of the script.

Why this answer

Option B is correct because `os.path.abspath(__file__)` returns the absolute path of the script file, and `os.path.dirname()` extracts the directory portion. This reliably gives the directory containing the main script, regardless of whether the script was invoked with a relative or absolute path. The `__file__` attribute contains the path used to execute the script, which may be relative; `os.path.abspath()` resolves it to an absolute path before extracting the directory.

Exam trap

Python Institute often tests the distinction between `os.path.abspath()` and `os.path.realpath()`, and the trap here is that candidates may choose Option A thinking they need to resolve symlinks, but the question only asks for the directory containing the script as executed, not the canonical path after symlink resolution.

How to eliminate wrong answers

Option A is wrong because `os.path.realpath(__file__)` resolves symbolic links, which is unnecessary and can lead to a different directory than the actual script location if symlinks are involved; the question only asks for the directory containing the main script, not the real path after symlink resolution. Option C is wrong because `os.getcwd()` returns the current working directory, which is the directory from which the Python interpreter was launched, not necessarily the directory containing the script; this is a common misconception. Option D is wrong because `os.path.abspath(__file__)` returns the full path to the script file itself, not the directory; it omits the `os.path.dirname()` call needed to extract the directory component.

344
MCQeasy

Which string method would you use to check if a string starts with a specified prefix?

A.start_with()
B.startswith()
C.beginswith()
D.startwithcase()
AnswerB

Correct method name.

Why this answer

The method is startswith(), which returns True if the string starts with the given prefix.

345
MCQhard

Refer to the exhibit. If 'data.txt' does not exist, what happens?

A.A NameError is raised because f is not defined in the finally block.
B.The function returns None.
C.A FileNotFoundError is raised and not caught.
D.The file is created and then closed.
AnswerA

f is not assigned due to the exception, so f.close() fails.

Why this answer

The open() call raises FileNotFoundError, so f is never assigned. The finally block tries to call f.close() on an undefined variable, causing a NameError.

346
MCQmedium

Consider the following class hierarchy: class A: def method(self): return 'A'; class B(A): pass; class C(A): def method(self): return 'C'; class D(B, C): pass. What is the output of D().method() according to Python's MRO?

A.'B'
B.TypeError
C.'A'
D.'C'
AnswerD

C's method() is found first in the MRO.

Why this answer

Python's MRO (Method Resolution Order) for class D(B, C) is computed using the C3 linearization algorithm, which respects the local precedence order and monotonicity. The MRO for D is D -> B -> C -> A, so D().method() resolves to C.method(), returning 'C'. Option D is correct because C is the first class in the MRO that defines method().

Exam trap

Python Institute often tests the C3 linearization rule that the MRO respects the order of base classes in the class definition, so candidates mistakenly think B's inheritance from A takes precedence over C's override, leading them to pick 'A' or 'B' instead of 'C'.

How to eliminate wrong answers

Option A is wrong because 'B' is not returned; class B does not override method(), so the MRO proceeds to C before reaching A. Option B is wrong because no TypeError occurs; the MRO is well-defined and method() is found in class C. Option C is wrong because 'A' is not returned; although A defines method(), the MRO finds C's override first, so A's version is never called.

347
MCQmedium

Refer to the exhibit. Which of the following is the most likely cause of this error?

A.The __init__.py file in mypackage is empty.
B.There is a circular import between mypackage and mymodule.
C.mymodule.py does not exist in mypackage directory.
D.mypackage is a module file, not a package directory.
AnswerD

If mypackage is a .py file, you cannot import 'mymodule' from it as a submodule.

Why this answer

Option D is correct because the error indicates that Python cannot import 'mypackage' as a package. If 'mypackage' is a single module file (e.g., mypackage.py) rather than a directory containing an __init__.py file, Python treats it as a module, not a package. This prevents the expected package-style import of submodules like 'mymodule', causing the ImportError.

Exam trap

Python Institute often tests the distinction between a package (directory with __init__.py) and a module (single .py file), trapping candidates who assume any directory can be imported as a package without the required __init__.py marker.

How to eliminate wrong answers

Option A is wrong because an empty __init__.py file is perfectly valid and still marks the directory as a Python package; the error would not occur solely due to an empty __init__.py. Option B is wrong because a circular import typically raises an ImportError with a different traceback (e.g., partially initialized module), not the specific error shown. Option C is wrong because if mymodule.py did not exist, the error would be 'ModuleNotFoundError: No module named mypackage.mymodule', not the generic ImportError about mypackage itself.

348
MCQeasy

A developer writes a script that reads a configuration file. If the file does not exist, the program should print an error and continue. Which code snippet correctly implements this behavior?

A.try: open('config.txt') except FileNotFoundError: print('File not found')
B.f = open('config.txt', 'r') if not f: print('File not found')
C.try: f = open('config.txt') except: print('File not found')
D.try: with open('config.txt') as f: pass except Exception: print('File not found')
AnswerA

Correctly catches only FileNotFoundError.

Why this answer

Option A is correct because it uses a `try` block to attempt opening the file and catches only `FileNotFoundError`, which is the specific exception raised when the file does not exist. This allows the program to print an error and continue execution without crashing, precisely matching the requirement.

Exam trap

Python Institute often tests the distinction between catching a specific exception versus a broad or bare `except`, and the trap here is that candidates may think any `try-except` works, overlooking the requirement to catch only `FileNotFoundError` for precise error handling.

How to eliminate wrong answers

Option B is wrong because `open()` does not return a falsy value when the file is missing; it raises a `FileNotFoundError` before any assignment occurs, so the `if not f` check is never reached. Option C is wrong because it uses a bare `except:` clause, which catches all exceptions (including unrelated ones like `KeyboardInterrupt` or `PermissionError`), violating best practices and potentially masking bugs. Option D is wrong because it catches the overly broad `Exception` class, which is too general and could hide unexpected errors; the requirement specifically needs to catch only `FileNotFoundError`.

349
MCQmedium

A developer is building a template system where placeholders like {name} and {age} appear in large text documents. They have a dictionary 'data' with the replacement values. Currently, they use a loop that calls str.replace() for each placeholder, e.g., for key, value in data.items(): text = text.replace('{' + key + '}', str(value)). This works, but performance is poor on large texts with many placeholders. The developer wants to use a more efficient method from the Python standard library. Which of the following is the best alternative?

A.Use text.format_map(data)
B.Use re.sub with a function that looks up the dictionary
C.Use an f-string with the dictionary unpacked as local variables
D.Use string.Template with data.safe_substitute
AnswerA

Efficient, built-in, single-pass replacement using dictionary mapping.

Why this answer

str.format_map() is designed for this purpose: it takes a mapping (like a dict) and substitutes placeholders of the form {key} in one pass, which is efficient. Option A (f-strings) requires knowing the variable names in advance. Option C (regex) is also efficient but requires importing re and writing a substitution function.

Option D (string.Template) is also a standard option but less efficient than format_map for dict lookups. Therefore, B is the best.

350
MCQmedium

A developer encounters an error: `ValueError: Unknown format code 's' for object of type 'int'` when running `print("{0:s}".format(42))`. What is the problem and how should it be fixed?

A.Change `{0:s}` to `{0:str}` to explicitly specify string conversion.
B.Wrap 42 in str(): `print("{0:s}".format(str(42)))`
C.Change `{0:s}` to `{0:i}` to indicate integer.
D.Change `{0:s}` to `{0:d}` because the value is an integer, not a string.
AnswerD

`d` is the correct format code for decimal integers.

Why this answer

Option D is correct because the format specifier `s` in `{0:s}` expects a string argument, but the provided argument `42` is an integer. The `d` format specifier is designed for integers, so changing `{0:s}` to `{0:d}` resolves the `ValueError` by matching the format code to the data type.

Exam trap

Python Institute often tests the distinction between format specifiers `s` and `d`, trapping candidates who think `s` can handle any type or who confuse `i` (from other languages like C) with Python's `d` for integers.

How to eliminate wrong answers

Option A is wrong because `{0:str}` is not a valid format specifier; Python's format specification mini-language uses single-letter codes like `s` and `d`, not type names. Option B is wrong because while wrapping `42` in `str()` would avoid the error, it is a workaround that converts the integer to a string unnecessarily, rather than fixing the root cause of using an incorrect format code for the original integer type. Option C is wrong because `i` is not a valid format code in Python's format specification; the correct code for integers is `d` (decimal).

351
MCQhard

Refer to the exhibit. What does the 'from None' clause do in the second raise statement?

A.It causes the original exception to be ignored.
B.It prevents chaining of exceptions, so only the final exception is displayed.
C.It causes both exceptions to be raised simultaneously.
D.It replaces the original exception with a new one.
AnswerB

The 'from None' disables exception chaining.

Why this answer

Using 'from None' suppresses the chained exception context, so only the second exception is shown.

352
MCQmedium

Inside a package 'data', there is a subpackage 'io' and a module 'utils'. Which import statement inside the 'io' subpackage correctly imports the 'helper' function from the sibling module 'utils'?

A.from ..utils import helper
B.import data.utils.helper
C.from .utils import helper
D.from data.io.utils import helper
AnswerA

Correct relative import: two dots refer to the parent package, then utils.

Why this answer

Option A is correct because the `..` prefix in a relative import refers to the parent package (`data`), and then `utils` is a sibling module of `io` within that parent package. This allows the `io` subpackage to import the `helper` function from the sibling module `utils` using `from ..utils import helper`.

Exam trap

Python Institute often tests the distinction between a single dot (`.` for same-package siblings) and double dots (`..` for parent-package siblings), causing candidates to mistakenly use `from .utils import helper` when the target module is in the parent package, not the current one.

How to eliminate wrong answers

Option B is wrong because `import data.utils.helper` is an absolute import that attempts to import a function directly, but Python requires importing the module first (e.g., `from data.utils import helper`). Option C is wrong because `from .utils import helper` uses a single dot, which refers to the current package (`data.io`), but there is no `utils` module inside `io`; it is a sibling, not a child. Option D is wrong because `from data.io.utils import helper` implies `utils` is a subpackage of `io`, but the problem states `utils` is a sibling module at the `data` package level, not inside `io`.

353
MCQhard

Which of the following exception classes is NOT a direct subclass of Exception in Python?

A.IOError
B.SystemExit
C.StopIteration
D.ValueError
AnswerB

SystemExit inherits from BaseException directly.

Why this answer

SystemExit is not a direct subclass of Exception; it inherits from BaseException instead. This is because SystemExit, along with KeyboardInterrupt and GeneratorExit, is intended to signal that the interpreter should exit, and catching it with a generic except Exception clause would be inappropriate. All other options (IOError, StopIteration, ValueError) are direct subclasses of Exception.

Exam trap

Python Institute often tests the distinction between BaseException and Exception, trapping candidates who assume all built-in exceptions inherit from Exception, when in fact SystemExit, KeyboardInterrupt, and GeneratorExit are direct subclasses of BaseException.

How to eliminate wrong answers

Option A is wrong because IOError is a direct subclass of Exception (and in Python 3, it is an alias of OSError, which also inherits from Exception). Option C is wrong because StopIteration is a direct subclass of Exception, used to signal the end of an iterator. Option D is wrong because ValueError is a direct subclass of Exception, raised when a built-in operation or function receives an argument with the right type but an inappropriate value.

354
MCQeasy

Refer to the exhibit. If the file config.cfg exists but the user does not have read permission, what will be printed?

A.An unhandled exception is raised
B.'Permission denied'
C.Nothing; the program continues silently
D.'File not found'
AnswerB

Correctly caught by PermissionError.

Why this answer

When the `open()` function is called on a file that exists but the user lacks read permission, Python raises a `PermissionError` exception. The code does not include a try-except block to handle this exception, so the program terminates with an unhandled exception and prints the error message 'Permission denied' (the string representation of the exception). Option B is correct because that is the default behavior of Python when such an exception is not caught.

Exam trap

Python Institute often tests the distinction between file existence errors (FileNotFoundError) and permission errors (PermissionError), and candidates mistakenly assume that a missing file is the only possible file-related exception.

How to eliminate wrong answers

Option A is wrong because an unhandled exception is indeed raised, but the question asks what will be printed — the exception's error message ('Permission denied') is printed, not just an unhandled exception without output. Option C is wrong because Python does not silently continue when a file permission error occurs; it raises an exception that must be caught to avoid termination. Option D is wrong because the file config.cfg exists (as stated in the question), so a 'File not found' error would only occur if the file did not exist, which is not the case here.

355
MCQmedium

Refer to the exhibit. Given the project structure, which of the following import statements in main.py would cause an ImportError?

A.from utils import strings
B.from ..utils import helpers
C.from utils import helpers
D.from utils.strings import format
AnswerB

Correct. Relative imports like '..' are allowed only inside a package; main.py is the top-level script.

Why this answer

Option B uses a relative import with '..' which is only valid inside a package (i.e., when the module is loaded as part of a package and has a __package__ attribute set). In a flat project structure where main.py is a top-level script, '..' attempts to go above the top-level package, which is not allowed and raises an ImportError. Python's import system requires that relative imports be used only within a package hierarchy.

Exam trap

Python Institute often tests the distinction between absolute and relative imports, trapping candidates who assume that '..' works in any script, when in fact relative imports are only valid inside a package and fail with an ImportError when used in a top-level script.

How to eliminate wrong answers

Option A is wrong because 'from utils import strings' is a valid absolute import that works when utils is a package (directory with __init__.py) containing a strings module; no ImportError occurs. Option C is wrong because 'from utils import helpers' is also a valid absolute import if helpers is a module or subpackage within utils; it does not cause an ImportError. Option D is wrong because 'from utils.strings import format' is a valid absolute import that imports the name 'format' from the strings module inside utils; as long as the module exists and contains that name, no ImportError occurs.

356
MCQhard

What is the result of the expression '123'.zfill(5)?

A.'00123'
B.'123'
C.'000123'
D.'12300'
AnswerA

Correct: Pads with two zeros on the left to reach length 5.

Why this answer

The `zfill()` method in Python pads the string on the left with zeros until it reaches the specified width. For the string '123' and width 5, it adds two zeros to the left, resulting in '00123'. This is the correct behavior as defined in Python's string methods.

Exam trap

Python Institute often tests the misconception that `zfill()` pads zeros on the right or that the width includes the original string length plus padding, leading candidates to choose options like '000123' or '12300'.

How to eliminate wrong answers

Option B is wrong because it represents the original string without any padding, ignoring the width parameter of 5. Option C is wrong because it adds three zeros, which would be the result for width 6, not 5. Option D is wrong because it pads zeros on the right, but `zfill()` always pads on the left, not the right.

357
MCQeasy

A developer is building an IoT application that reads temperature data from a sensor over a TCP socket. The sensor sends data as a stream of bytes encoded in UTF-8, with each reading terminated by a newline character. The developer uses the following code to receive data: ```python import socket s = socket.socket() s.connect(('sensor.local', 5000)) data = s.recv(1024) ``` The variable `data` is a bytes object. The developer needs to convert it to a string to parse the temperature value. Which of the following lines of code should the developer use to correctly obtain the string representation of the received data, assuming the data is valid UTF-8 and may contain non-ASCII characters?

A.data.encode('utf-8')
B.data.decode('utf-8')
C.bytes(data)
D.str(data)
AnswerB

Correctly decodes UTF-8 bytes to a string.

Why this answer

Option A is correct because `decode('utf-8')` converts bytes to a string using UTF-8 encoding, which is correct for this scenario. Option B is wrong because `str(data)` returns a string representation of the bytes object (e.g., "b'...'"), not the decoded text. Option C is wrong because `encode` is used to convert string to bytes, not the reverse.

Option D is wrong because `bytes(data)` returns the same bytes object, not a string.

358
Multi-Selectmedium

Which TWO of the following are appropriate techniques for logging exception details in Python? (Select exactly 2)

Select 2 answers
A.Using print(e.args)
B.Using traceback.format_exc()
C.Using sys.exc_info()
D.Using raise without argument
E.Using logging.exception() inside except block
AnswersB, E

Returns traceback string, suitable for logging.

Why this answer

Option B is correct because `traceback.format_exc()` returns the full traceback as a string, which can be logged or printed to capture detailed exception context. Option E is correct because `logging.exception()` automatically includes the traceback of the current exception when called inside an `except` block, making it the idiomatic way to log exceptions in Python.

Exam trap

Python Institute often tests the distinction between merely accessing exception data (like `e.args` or `sys.exc_info()`) and actually formatting or logging it properly, so candidates mistakenly think any function that touches exception info qualifies as a 'logging technique'.

359
MCQhard

Consider the following code snippet: 'class A: pass; class B(A): pass; class C(A): pass; class D(B, C): pass'. What is the Method Resolution Order (MRO) for class D according to the C3 linearization algorithm used by Python?

A.D, B, A, C, object
B.D, B, C, A
C.D, B, A, object, C
D.D, B, C, A, object
AnswerD

Correct linearization based on C3.

Why this answer

The C3 linearization algorithm merges the linearizations of D's parents (B and C) with their parent list, respecting the local precedence order and monotonicity. For class D(B, C), the MRO is computed as D + merge(L(B), L(C), [B, C]), where L(B) = B, A, object and L(C) = C, A, object. The merge yields D, B, C, A, object, which is the correct MRO.

Exam trap

Python Institute often tests the misconception that Python uses depth-first left-to-right resolution (like in old-style classes), leading candidates to pick Option A (D, B, A, C, object) instead of the correct C3 linearization result.

How to eliminate wrong answers

Option A is wrong because it incorrectly places A before C, violating the local precedence order where C should appear before A (since D inherits from B then C, and C is a direct parent). Option B is wrong because it omits 'object', which is always the final class in the MRO for new-style classes in Python. Option C is wrong because it places 'object' before C, which breaks monotonicity and the rule that a parent's MRO must be preserved; C must appear before object.

360
MCQmedium

You are a Python developer working on a project with the following structure: myapp/ __init__.py main.py modules/ __init__.py utils.py helpers.py The file main.py contains: from modules import utils from modules import helpers utils.some_function() helpers.another_function() When you run main.py, you get an ImportError: No module named 'modules'. However, the modules directory exists and both __init__.py files are present. The directory myapp is not installed as a package; you are running main.py directly from the myapp directory. What is the most likely cause and how should you fix it?

A.Move main.py to the parent directory of myapp and use 'from myapp.modules import utils' or run with 'python -m myapp.main' from the parent.
B.Add the parent directory of myapp to sys.path at the beginning of main.py.
C.Add an __all__ variable in modules/__init__.py to explicitly export the submodules.
D.Rename modules/__init__.py to something else.
AnswerA

This ensures myapp is treated as a package and imports are absolute.

Why this answer

Option A is correct because when running main.py directly, Python adds the directory containing main.py (myapp) to sys.path, not its parent. Since 'modules' is a subdirectory of myapp, Python cannot find it as a top-level module. Moving main.py to the parent directory or using the -m flag (which sets the working directory as the script's location) allows 'from myapp.modules import utils' to resolve correctly, as myapp becomes a package.

Exam trap

Python Institute often tests the distinction between running a script directly (which adds the script's directory to sys.path) versus using the -m flag (which adds the current working directory), and candidates mistakenly think that having __init__.py files alone is sufficient for any import style.

How to eliminate wrong answers

Option B is wrong because adding the parent directory of myapp to sys.path would still not make 'modules' importable as a top-level name; Python would need 'from myapp.modules import utils' or a relative import. Option C is wrong because __all__ controls what is exported with 'from module import *', not the ability to import the module itself; the ImportError occurs because 'modules' is not found as a package, not because of missing exports. Option D is wrong because renaming or removing __init__.py would break the package structure entirely, preventing Python from recognizing 'modules' as a package at all.

361
MCQhard

You are a developer at a company that builds a data processing pipeline. The pipeline consists of several Python modules organized in a package called 'pipeline'. The package structure is: pipeline/ __init__.py load.py transform.py analyze.py The pipeline is deployed on a server where Python 3.8 is installed. The server also has a globally installed package called 'pipeline' (from a different project) in the site-packages directory. When you run your scripts that import 'pipeline', you get unexpected behavior because Python is importing the wrong package. You need to ensure that your local 'pipeline' package is used instead of the global one. You cannot uninstall the global package because it is used by another application. You have the following options: A) Modify the PYTHONPATH environment variable to include the directory containing your 'pipeline' package before the site-packages directory. B) Rename your local 'pipeline' package to something else and update all imports. C) Use a virtual environment specific to your project and install your package there. D) Add an __init__.py file with a special import hook to override the global package. Which course of action is the most appropriate and reliable?

A.Use a virtual environment specific to your project and install your package there.
B.Add an __init__.py file with a special import hook to override the global package.
C.Rename your local 'pipeline' package to something else and update all imports.
D.Modify the PYTHONPATH environment variable to include the directory containing your 'pipeline' package before the site-packages directory.
AnswerA

Virtual environments provide clean isolation and are best practice.

Why this answer

Option A is correct because using a virtual environment creates an isolated Python environment where you can install your local 'pipeline' package without affecting or being affected by the globally installed package. This is the most reliable approach as it ensures that Python's import system will search the virtual environment's site-packages before the global site-packages, preventing any naming conflicts. Virtual environments are the standard Python best practice for managing project-specific dependencies and avoiding package name collisions.

Exam trap

The trap here is that candidates often assume modifying PYTHONPATH is a simple and effective solution, but Cisco tests the understanding that PYTHONPATH does not always override site-packages reliably, especially in modern Python versions, making virtual environments the only robust and recommended approach.

How to eliminate wrong answers

Option B is wrong because adding an __init__.py file with a special import hook is not a standard or reliable mechanism to override a global package; Python's import system does not support such hooks in a way that would consistently bypass the global package, and this approach is fragile and non-portable. Option C is wrong because renaming your local package is a workaround that does not solve the underlying import order issue; it also requires updating all imports across the codebase, which is error-prone and does not prevent future conflicts if another package with the same name is installed. Option D is wrong because modifying PYTHONPATH to include your local package directory before site-packages is unreliable; the order of directories in PYTHONPATH is not guaranteed to take precedence over site-packages in all Python versions or configurations, and it can be easily overridden by other environment settings or by the way Python initializes its import path.

362
MCQmedium

Refer to the exhibit. What is the output of the code?

A.Program
B.Programming
C.Python Programming
D.Python
AnswerB

Index 7 is the 'P' of 'Programming', slice from there to end.

Why this answer

The code uses slicing with `[::2]` on the string 'Python Programming', which returns every second character starting from the first. The result is 'Pto rgamn', but the question likely expects the output of a different operation or the code is misrepresented. However, based on the provided correct answer 'Programming', the code must be extracting a substring or using a method like `split()` or slicing with specific indices.

Given the options, 'Programming' is the substring from index 7 to the end of 'Python Programming' (since 'Python ' is 7 characters), which is obtained by `'Python Programming'[7:]`.

Exam trap

Python Institute often tests whether candidates confuse slicing indices with character positions, leading them to miscount and pick 'Program' (7 characters) instead of 'Programming' (11 characters) when extracting from index 7 onward.

How to eliminate wrong answers

Option A is wrong because 'Program' is only the first 7 characters of 'Programming', missing the final 'ming'. Option C is wrong because 'Python Programming' is the original string, not the output of any slicing or method that would extract a substring. Option D is wrong because 'Python' is the first 6 characters, which would require slicing `[:6]`, but the code does not produce that.

363
MCQmedium

What will the above code output?

A.Index out of range
B.The program runs without output.
C.The program crashes with an unhandled IndexError.
D.ValueError is raised.
AnswerA

IndexError occurs and the except block prints this message.

Why this answer

Option B is correct because accessing index 100 on a string of length 11 raises an IndexError, which is caught and the message is printed. Option A would happen if the error were not caught. Option C is not thrown.

Option D is false because the error is caught and the except block runs.

364
MCQmedium

A developer needs to create a class that cannot be instantiated directly but serves as a base for other classes. Which approach should be used?

A.Define __init__ that raises NotImplementedError
B.Define the class using the ABCMeta metaclass and decorate methods with @abstractmethod
C.Use a naming convention like _BaseClass
D.Define __new__ to return None
AnswerA

This prevents direct instantiation; subclasses must override __init__.

Why this answer

Option A is correct because raising `NotImplementedError` in the `__init__` method prevents direct instantiation of the class while still allowing subclasses to override `__init__` and be instantiated. This is a common Python pattern for creating abstract base classes without using the `abc` module, though it does not enforce abstraction at the method level.

Exam trap

Python Institute often tests the distinction between runtime enforcement (raising `NotImplementedError`) and compile-time enforcement (using `abc.ABC`), and the trap here is that candidates may choose option B because it is the more 'proper' abstract base class approach, but the question explicitly asks for a class that 'cannot be instantiated directly' and serves as a base — the `NotImplementedError` pattern is the specific technique they want, not the full `abc` module.

How to eliminate wrong answers

Option B is wrong because using `ABCMeta` and `@abstractmethod` creates a true abstract base class that cannot be instantiated, but the question asks for a class that 'cannot be instantiated directly' — this is also a valid approach, but the question specifically expects the pattern of raising `NotImplementedError` in `__init__`, making A the intended answer. Option C is wrong because a naming convention like `_BaseClass` is just a convention and does not prevent instantiation; Python does not enforce private naming. Option D is wrong because defining `__new__` to return `None` would prevent instantiation entirely, but it would also break subclass instantiation (since `__new__` is called before `__init__`), and returning `None` from `__new__` causes `__init__` not to be called, which is not the intended behavior for a base class that should be subclassed.

365
MCQhard

Given the code above, what is printed? Note: each backslash is a single character.

A.21
B.23
C.22
D.24
AnswerB

Counting each character: C, :, \, U, s, e, r, s, \, J, o, h, n, \, D, o, c, u, m, e, n, t, s -> total 23.

Why this answer

Option D is correct. The raw string r"..." treats backslashes as literal characters. The path has: C, :, \, U, s, e, r, s, \, J, o, h, n, \, D, o, c, u, m, e, n, t, s.

That's 23 characters. Option A counts standard string escape sequences (e.g., \U would be interpreted as Unicode if not raw). Option B and C are other miscalculations.

366
MCQhard

A class has a class attribute that is a list. A developer modifies this list via one instance, and the change is reflected in all other instances. What is the best practice to avoid this unintended sharing?

A.Use a tuple instead of a list.
B.Initialize the list in `__init__` rather than as a class attribute.
C.Use a class method to modify the list.
D.Use `deepcopy` when accessing the list.
AnswerB

By creating the list in `__init__`, each instance gets its own independent list.

Why this answer

Option B is correct because class attributes are shared across all instances. By initializing the list inside `__init__`, each instance gets its own independent list object, preventing unintended mutation from affecting other instances. This is the standard Python pattern for instance-specific mutable data.

Exam trap

Python Institute often tests the distinction between class-level and instance-level attributes, and the trap here is that candidates mistakenly think using a tuple (immutable) or a class method solves the sharing problem, when the real issue is the location of the mutable object's definition.

How to eliminate wrong answers

Option A is wrong because using a tuple prevents mutation entirely, which is not a solution for the requirement to modify the list; it changes the data structure's semantics and would cause an AttributeError on attempted modification. Option C is wrong because a class method still operates on the class-level list, so modifying it via one instance would still affect all instances; the sharing issue is not about the method type but about where the list is stored. Option D is wrong because `deepcopy` only creates a copy at the time of access, but the underlying class attribute remains shared; repeated accesses would require manual copying each time, which is inefficient and does not solve the fundamental design problem.

367
MCQhard

Refer to the exhibit. A developer ran the script and saw the above traceback. The intended behavior was to load a JSON configuration file, and if the file is missing, create a default config. What is the most likely root cause of the second exception (NameError)?

A.The variable 'f' was not defined due to the FileNotFoundError.
B.The script did not import the json module.
C.The config.json file exists but is empty.
D.The file was opened in binary mode instead of text mode.
AnswerB

NameError: name 'json' is not defined indicates the import is missing.

Why this answer

Option B is correct because the traceback shows a NameError for 'json.loads', which indicates that the name 'json' is not defined in the current namespace. This occurs when the script attempts to call json.loads() without first importing the json module. The intended behavior of loading a JSON configuration file requires the json module to parse the file content, and its absence causes the NameError exception.

Exam trap

Python Institute often tests the distinction between file I/O exceptions (like FileNotFoundError) and name resolution errors (NameError), trapping candidates who focus on the file handling part of the traceback rather than recognizing that the second exception is about an undefined module name.

How to eliminate wrong answers

Option A is wrong because the NameError occurs after the FileNotFoundError is handled (the traceback shows the exception chain), and the variable 'f' is not referenced in the json.loads() call; the error is about the name 'json', not 'f'. Option C is wrong because an empty file would not cause a NameError; it would cause a json.JSONDecodeError when trying to parse empty content, not a missing name. Option D is wrong because opening a file in binary mode (e.g., 'rb') would not cause a NameError; it would affect how the file content is read (bytes vs string), but the json.loads() function can still be called if the module is imported, and the error would be a TypeError or similar, not a NameError.

368
Multi-Selectmedium

A developer is validating user input in a Python application. The string variable `input_str` is assigned the value `'Hello World'`. Which TWO of the following conditions evaluate to `True`? (Choose two.)

Select 2 answers
A.input_str.isalpha()
B.input_str.istitle()
C.input_str.isprintable()
D.input_str.isalnum()
E.input_str.isspace()
AnswersB, C

The string is titlecased.

Why this answer

Option A is correct because the string 'Hello World' is titlecased (each word starts with an uppercase letter and the rest are lowercase). Option E is correct because all characters in the string are printable (no control characters). Option B is false because the string contains non-space characters.

Option C is false because the string contains a space, which is not alphabetic. Option D is false because the string contains a space, which is not alphanumeric.

369
Multi-Selecteasy

Which TWO of the following are valid ways to define a class attribute (as opposed to an instance attribute) in Python?

Select 2 answers
A.obj.attr = 5 on an instance
B.class MyClass: def method(self): pass
C.class MyClass: def __init__(self): self.attr = 5
D.class MyClass: attr = 5
E.MyClass.attr = 5 outside the class definition
AnswersD, E

Class variable assignment inside the class body.

Why this answer

Option D is correct because defining `attr = 5` directly inside the class body, but outside any method, creates a class attribute that is shared by all instances. This is the standard Python syntax for class-level data.

Exam trap

Python Institute often tests the distinction between class attributes and instance attributes by presenting options that look similar (e.g., `self.attr` vs. `ClassName.attr`), and the trap is that candidates confuse assignment inside `__init__` (instance) with assignment in the class body (class).

370
MCQhard

Consider the following code snippet: s = 'abcdefgh'; result = s[7:3:-2]; print(result). What is the output?

A.fh
B.hf
C.h
D.hfd
AnswerB

Slice indices: start=7 ('h'), end=3 (excluded), step=-2, so characters at 7 and 5: 'h' and 'f'. Output: 'hf'.

Why this answer

Option D is correct. The slice s[7:3:-2] starts at index 7 ('h'), goes backwards with step -2, and stops before index 3. Index 7 -> 'h'; index 5 -> 'f'; index 3 is the stop (exclusive), so not included.

Thus result = 'hf'. Option A would be 'hfd' if stop were 2. Option B gives only 'h'.

Option C gives 'hf' but with different order? Actually 'fh' is reverse order of what the step produces.

371
MCQhard

A web application receives a byte string b'\xc3\xa9' which represents the character 'é' in UTF-8. The developer wants to convert it to a Python string. Which operation should be used?

A.b'\xc3\xa9'.encode('utf-8')
B.b'\xc3\xa9'.tostring()
C.str(b'\xc3\xa9', 'ascii')
D.b'\xc3\xa9'.decode('utf-8')
AnswerD

Correct: .decode('utf-8') converts the bytes to a string.

Why this answer

The decode() method converts bytes to a string using the specified encoding. .decode('utf-8') is correct.

372
MCQmedium

You are developing a Python application that processes financial transactions. The application is structured as a package named `finance`. Inside `finance`, there are subpackages: `models`, `services`, and `utils`. The `services` subpackage contains a module `validator.py` that defines a function `validate_transaction()`. This function uses a helper function `check_amount()` defined in `utils.helpers`. The package is used by multiple other projects, and you want to ensure that importing `finance` does not accidentally expose internal helper functions. You also want to allow users to easily import the main validation function via `from finance import validate_transaction`. Which of the following approaches best achieves these goals?

A.In `finance/__init__.py`, write `from . import services` and `from .services import validator`. Then users can call `finance.services.validator.validate_transaction()`.
B.In `finance/__init__.py`, write `from .services.validator import validate_transaction`. Then users can call `finance.validate_transaction()`.
C.In `finance/__init__.py`, write `from .services import validator`. Then users can call `finance.validator.validate_transaction()`.
D.In `finance/__init__.py`, write `from .utils.helpers import *` and `from .services.validator import validate_transaction`.
AnswerB

This imports only the needed function, keeping helpers private.

Why this answer

Option B is correct because it imports the `validate_transaction` function directly into the `finance` package namespace via `from .services.validator import validate_transaction` in `finance/__init__.py`. This allows users to use `from finance import validate_transaction` as desired, while keeping internal helper functions like `check_amount` in `utils.helpers` unexposed, since they are not imported into the package's top-level namespace. This approach follows the principle of explicit imports and encapsulation.

Exam trap

Python Institute often tests the distinction between importing a module versus importing a specific name from a module, and the trap here is that candidates may think importing the module (e.g., `from .services import validator`) is sufficient to allow `from finance import validate_transaction`, when in fact it only makes `finance.validator` available, not the function directly.

How to eliminate wrong answers

Option A is wrong because it only imports the `services` subpackage and the `validator` module, requiring users to call `finance.services.validator.validate_transaction()`, which does not satisfy the requirement of importing via `from finance import validate_transaction`. Option C is wrong because it imports the `validator` module into the `finance` namespace, so users would call `finance.validator.validate_transaction()` instead of `finance.validate_transaction()`, failing the desired import pattern. Option D is wrong because it uses `from .utils.helpers import *`, which exposes all names from `helpers` (including the internal `check_amount`) into the `finance` namespace, violating the goal of not accidentally exposing internal helper functions.

373
MCQhard

A developer appends a custom path to sys.path and then tries to import a function from a module: import sys; sys.path.append('/custom/libs'); from mylib import func. The import fails with ModuleNotFoundError. mylib is a directory. What is the most likely cause?

A.The import order is wrong; sys.path.append should be after the import.
B.mylib.py exists in the same directory as the script.
C.The appended path does not exist on the filesystem.
D.The mylib directory lacks an __init__.py file.
AnswerD

Without __init__.py, the directory is not recognized as a package.

Why this answer

Option D is correct because when importing from a directory (package), Python requires an `__init__.py` file (even if empty) in that directory to treat it as a package. Without it, Python does not recognize `mylib` as a package, so `from mylib import func` fails with `ModuleNotFoundError`. This is a fundamental requirement for regular packages in Python (prior to namespace packages in Python 3.3+).

Exam trap

Python Institute often tests the misconception that adding a directory to `sys.path` is sufficient to import from it, but the trap is that the directory must be a proper package with an `__init__.py` file, otherwise Python will not treat it as a module or package.

How to eliminate wrong answers

Option A is wrong because `sys.path.append` must occur before the import to add the custom path to the module search list; placing it after would have no effect, but the error here is not about order. Option B is wrong because if `mylib.py` existed in the same directory, the import would succeed (assuming the script's directory is already in `sys.path`), but the question states `mylib` is a directory, not a file. Option C is wrong because even if the appended path does not exist, Python would simply skip it during module search and continue looking elsewhere; the error would only occur if no valid path contains the module, but the core issue here is the missing `__init__.py` inside the directory.

374
Multi-Selectmedium

Which THREE of the following string methods can be used to split a string into a list of substrings? (Choose three.)

Select 3 answers
A.splitlines()
B.split()
C.join()
D.rsplit()
E.partition()
AnswersA, B, D

Correct: Splits on line boundaries and returns a list of lines.

Why this answer

split() splits on whitespace or a delimiter and returns a list of substrings. rsplit() does the same from the right. splitlines() splits on line boundaries into a list. partition() returns a tuple, not a list.

375
MCQeasy

A programmer wants to create a package named 'analytics' with subpackages 'statistics' and 'ml'. Which directory structure correctly defines these packages?

A.analytics/, analytics/statistics/ (__init__.py), analytics/ml/ (__init__.py)
B.analytics/ (__init__.py), analytics/statistics/ (__init__.py), analytics/ml/ (__init__.py), analytics/__init__.py (file)
C.analytics/ (__init__.py), analytics/statistics/, analytics/ml/
D.analytics/ (__init__.py), analytics/statistics/ (__init__.py), analytics/ml/ (__init__.py)
AnswerD

Each directory must contain an __init__.py file to be recognized as a package.

Why this answer

In Python, a directory is recognized as a package only if it contains an `__init__.py` file (even if empty). To create the 'analytics' package with 'statistics' and 'ml' subpackages, each directory must have its own `__init__.py`. Option D correctly places `__init__.py` in all three directories: `analytics/`, `analytics/statistics/`, and `analytics/ml/`.

Exam trap

Python Institute often tests the misconception that only the top-level package needs an `__init__.py` file, or that subdirectories without `__init__.py` are still valid subpackages, leading candidates to pick option C or A.

How to eliminate wrong answers

Option A is wrong because the top-level `analytics/` directory lacks an `__init__.py` file, so Python will not treat it as a package, making subpackage imports fail. Option B is wrong because it redundantly lists `analytics/__init__.py` twice (once as a parenthesized file and once as a separate entry), which is syntactically incorrect and implies a duplicate file; the correct structure requires exactly one `__init__.py` per directory. Option C is wrong because the subdirectories `analytics/statistics/` and `analytics/ml/` do not contain `__init__.py` files, so they are not recognized as Python packages, only as ordinary directories.

Page 4

Page 5 of 7

Page 6

All pages