Certified Associate Python Programmer PCAP (PCAP) — Questions 76150

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

Page 1

Page 2 of 7

Page 3
76
Multi-Selecteasy

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

Select 2 answers
A.The __init__.py file must contain at least one import statement.
B.It can be used to define the __all__ variable for package exports.
C.It can execute arbitrary code when the package is imported.
D.It must be named exactly __init__.py, with no other possible names.
E.It is executed every time a submodule is imported.
AnswersB, C

Defining __all__ in __init__.py controls what is exported with 'from package import *'.

Why this answer

Option B is correct because the `__init__.py` file can define the `__all__` variable, which is a list of module names that will be exported when a client uses `from package import *`. This controls the public API of the package by specifying which submodules or names are accessible via wildcard imports.

Exam trap

Python Institute often tests the misconception that `__init__.py` is required for every package (it is not in Python 3.3+ due to implicit namespace packages) and that it must contain imports or code (it can be empty and still work).

77
Matchingmedium

Match each code snippet to its output.

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

Concepts
Matches

8

3

1

15

14

Why these pairings

Basic arithmetic operations and operator precedence.

78
MCQmedium

Refer to the exhibit. A developer is writing a script to read this JSON configuration file. The script should write the logging configuration to a separate file called 'logging.conf'. Which file mode should be used to create the file if it doesn't exist, and overwrite it if it does?

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

Mode 'w' opens for writing, truncating existing file or creating new one.

Why this answer

Option D ('w') is correct because the 'w' mode opens a file for writing, truncating it first if it exists, and creating it if it does not. This matches the requirement to overwrite an existing 'logging.conf' file or create a new one if absent.

Exam trap

Python Institute often tests the distinction between 'w' and 'x' modes, where candidates mistakenly choose 'x' thinking it creates a new file, forgetting that 'x' raises an error if the file already exists, thus failing the overwrite requirement.

How to eliminate wrong answers

Option A ('x') is wrong because 'x' is an exclusive creation mode that raises a FileExistsError if the file already exists, so it cannot overwrite an existing file. Option B ('r+') is wrong because 'r+' opens a file for reading and writing but does not create the file if it does not exist; it raises a FileNotFoundError. Option C ('a') is wrong because 'a' opens a file for appending, which does not overwrite existing content; it writes new data at the end of the file.

79
MCQmedium

A package 'shapes' has an __init__.py file. Which statement must be included in the __init__.py file to allow the syntax 'from shapes import *' to import all submodules 'circle', 'square', and 'triangle'?

A.Set __all__ to an empty list
B.__all__ = ['circle', 'square', 'triangle'] and import each submodule
C.Import each submodule in __init__.py without defining __all__
D.__all__ = ['circle', 'square', 'triangle']
AnswerD

Correctly defines the list of submodule names to be imported with '*'. This is the standard mechanism.

Why this answer

Option D is correct because the `__all__` variable in `__init__.py` explicitly defines the list of submodule names that should be imported when `from shapes import *` is executed. Setting `__all__ = ['circle', 'square', 'triangle']` tells Python to import only those submodules, which is the standard mechanism for controlling wildcard imports from a package.

Exam trap

Python Institute often tests the misconception that simply importing submodules in `__init__.py` is sufficient for `from shapes import *` to work, when in reality the `__all__` list is required to explicitly control wildcard imports from a package.

How to eliminate wrong answers

Option A is wrong because setting `__all__` to an empty list would cause `from shapes import *` to import nothing, not the three required submodules. Option B is wrong because while it correctly defines `__all__`, it also requires importing each submodule explicitly; however, the `__all__` list alone is sufficient to trigger Python's package import mechanism for the listed submodules, and the extra import statements are unnecessary for the wildcard import to work. Option C is wrong because without defining `__all__`, `from shapes import *` will import only names defined in `__init__.py` that are not prefixed with an underscore, but it will not automatically import submodules unless they are explicitly imported or `__all__` is set.

80
MCQmedium

Given `s = 'Python'`, what is the result of `s[-4::-1]`?

A.'ty'
B.'tho'
C.'nohtyP'
D.'tyP'
AnswerD

Starts at -4 and steps backward to start.

Why this answer

Option C is correct: `s[-4::-1]` starts at index -4 (which is 't' in 'Python' since indices: P=0, y=1, t=2, h=3, o=4, n=5; negative: n=-1, o=-2, h=-3, t=-4, y=-5, P=-6), and steps backwards by -1 to the beginning, so it takes characters at indices -4, -5, -6 which are 't', 'y', 'P' -> 'tyP'. Option A is wrong because it slices from -4 to end. Option B is the reverse of the whole string.

Option D is slicing from -4 to 0 with step -1 (exclusive of 0? Actually -4:-1:1 gives 'tho'? Let's not confuse).

81
MCQmedium

Refer to the exhibit. What is printed?

A.' Alice is 025 years old.'
B.' Alice is 25 years old.'
C.'Alice is 25 years old.'
D.' Alice is 25 years old.'
AnswerA

Correct: name right-aligned, age zero-padded.

Why this answer

The format specifier >10 right-aligns name in a field of 10 characters, and 03d zero-pads age to three digits. So output: ' Alice is 025 years old.'

82
MCQmedium

Two modules, 'module_a' and 'module_b', import each other. When 'module_a' is imported first, it tries to import 'module_b', which in turn tries to import 'module_a' again, causing a circular import error. Which of the following is the most effective strategy to resolve this circular dependency?

A.Move the shared code into a third module that both can import.
B.Place all code in a single module.
C.Use relative imports instead of absolute imports.
D.Use the import statement inside function definitions to defer imports.
AnswerA

Eliminates the circular dependency by extracting shared functionality into a separate module.

Why this answer

Option A is the most effective because it removes the circular dependency entirely. Option D (lazy import) can work but is often considered a workaround; restructuring is cleaner. Options B and C are not standard solutions.

83
Multi-Selecthard

Which THREE factors can cause an 'ImportError' when trying to import a module?

Select 3 answers
A.The module file has a syntax error.
B.The module is a C extension that fails to load.
C.The module has a circular import.
D.The module is not in the search path.
E.The module's __init__.py is empty.
AnswersB, C, D

Correct. If a C extension fails to load (e.g., missing library), an ImportError is raised.

Why this answer

Option B is correct because if a module is a C extension (e.g., a .so or .pyd file) and it fails to load due to missing dependencies, incompatible architecture, or a linking error, Python raises an ImportError. This is distinct from a syntax error in Python source code, which would raise a SyntaxError, not an ImportError.

Exam trap

Python Institute often tests the distinction between ImportError and other exceptions like SyntaxError or ModuleNotFoundError, and the trap here is that candidates may incorrectly think a syntax error in a module causes an ImportError, when in fact it raises a SyntaxError at import time.

84
Multi-Selectmedium

Which TWO statements about inheritance in Python are true?

Select 2 answers
A.Abstract base classes can be instantiated if they have no abstract methods.
B.The Method Resolution Order (MRO) is determined by the C3 linearization algorithm.
C.Private attributes (with double underscore) of the base class are accessible in the subclass.
D.A class can inherit from multiple base classes.
E.The super() function returns a proxy object for method delegation.
AnswersB, D

C3 linearization is used to compute MRO in Python.

Why this answer

Option B is correct because Python's Method Resolution Order (MRO) is determined by the C3 linearization algorithm, which ensures a consistent and predictable order for method lookup in multiple inheritance scenarios. This algorithm produces a linearization that respects the local precedence order and monotonicity, as defined in the Python documentation for class hierarchies.

Exam trap

Python Institute often tests the misconception that `super()` returns a direct parent class instance, when in fact it returns a proxy that follows the MRO, which is essential for cooperative multiple inheritance in Python.

85
MCQhard

A script reads a binary file and decodes it as UTF-8. Some bytes are invalid UTF-8 sequences, causing a `UnicodeDecodeError`. The developer wants to replace invalid bytes with the replacement character U+FFFD. Which approach achieves this?

A.data.decode('utf-8', errors='strict')
B.data.decode('utf-8', errors='surrogateescape')
C.data.decode('utf-8', errors='replace')
D.data.decode('utf-8', errors='ignore')
AnswerC

Replaces invalid bytes with U+FFFD.

Why this answer

Option C is correct because the `errors='replace'` parameter in Python's `decode()` method replaces any bytes that cannot be decoded as valid UTF-8 with the Unicode replacement character U+FFFD, which is exactly what the developer wants. This approach ensures the script continues processing without raising a `UnicodeDecodeError` while preserving the overall structure of the data.

Exam trap

Python Institute often tests the distinction between `errors='replace'` and `errors='ignore'`, where candidates mistakenly choose 'ignore' thinking it handles errors gracefully, but the trap is that 'ignore' silently drops invalid bytes instead of inserting a visible placeholder, which can lead to unintended data concatenation or loss of positional alignment.

How to eliminate wrong answers

Option A is wrong because `errors='strict'` is the default behavior that raises a `UnicodeDecodeError` on invalid UTF-8 sequences, which the developer explicitly wants to avoid. Option B is wrong because `errors='surrogateescape'` replaces invalid bytes with surrogate code points (U+DC80–U+DCFF) rather than the replacement character U+FFFD, which is intended for round-tripping binary data through strings, not for producing clean Unicode output. Option D is wrong because `errors='ignore'` silently removes invalid bytes without any replacement, which can corrupt the data stream and lose information, whereas the developer wants to replace invalid bytes with a visible placeholder.

86
MCQhard

A Python script reads a file containing text with non-ASCII characters like 'é' and 'ü'. The script must encode the string as UTF-8 then decode it back. Which of the following correctly handles this without error?

A.s.decode('utf-8').encode('utf-8')
B.s.encode('ascii').decode('ascii')
C.s.encode('utf-8').decode('utf-8')
D.s.decode('utf-8').decode('utf-8')
AnswerC

Encoding to bytes then decoding back with the same codec works correctly.

Why this answer

Option C is correct because it first encodes the string (which contains non-ASCII characters like 'é' and 'ü') into UTF-8 bytes using `.encode('utf-8')`, then decodes those bytes back into a string using `.decode('utf-8')`. This round-trip preserves all characters since UTF-8 can represent any Unicode code point, and the operations are applied in the correct order: a string is encoded to bytes, then bytes are decoded back to a string.

Exam trap

Python Institute often tests the distinction between string and bytes methods — the trap here is that candidates confuse `.encode()` and `.decode()`, thinking both can be called on strings, or they incorrectly assume ASCII can handle non-ASCII characters without error.

How to eliminate wrong answers

Option A is wrong because it attempts to decode a string (which is already a Unicode object) using `.decode('utf-8')`, which raises an `AttributeError` — decode is a method of bytes, not str. Option B is wrong because it encodes the string to ASCII, which will raise a `UnicodeEncodeError` for non-ASCII characters like 'é' and 'ü' since ASCII only supports code points 0–127. Option D is wrong because it calls `.decode()` twice on a string, which is invalid for the same reason as Option A — the first decode fails, and even if it were bytes, double decoding would produce garbage or an error.

87
MCQmedium

A developer creates classes `A`, `B(A)`, `C(A)`, and `D(B, C)`. When calling a method from `D` that is defined in `A`, which class's version is used according to Python's MRO?

A.The method from B, because it is the first parent.
B.The method from C, because it appears after B.
C.The method from A, but only if B and C do not override it.
D.The method from A, found through B then C.
AnswerD

MRO is D -> B -> C -> A, so the first parent with the method is A after traversing B and C.

Why this answer

Python's Method Resolution Order (MRO) for class `D(B, C)` follows the C3 linearization algorithm, which ensures a depth-first left-to-right search while preserving monotonicity. For `D(B, C)`, the MRO is `D -> B -> C -> A`, so a method defined in `A` that is not overridden in `B` or `C` will be found via `B` first, then `C`, and finally `A`. Option D correctly states that the method from `A` is used, found through `B` then `C`, which matches the actual resolution path.

Exam trap

Python Institute often tests the misconception that Python's MRO simply searches the first parent and its ancestors before moving to the next parent (depth-first left-to-right), but the actual C3 linearization can produce a different order, especially in diamond inheritance, and candidates may incorrectly assume the method from `A` is found directly without considering the intermediate classes in the MRO.

How to eliminate wrong answers

Option A is wrong because it assumes the first parent's version is always used, but Python's MRO does not simply stop at the first parent; it uses C3 linearization to consider all ancestors in a specific order, and if `B` does not override the method, the search continues to `C` and then `A`. Option B is wrong because it incorrectly suggests that `C`'s version is used because it appears after `B` in the class definition, but the MRO for `D(B, C)` is `D -> B -> C -> A`, so `B` is checked before `C`, and the method from `A` is only reached if neither `B` nor `C` overrides it. Option C is wrong because it implies the method from `A` is used only if `B` and `C` do not override it, which is true, but it omits the critical detail that the resolution path goes through `B` then `C` before reaching `A`, and the statement 'found through B then C' is essential to understanding MRO; the option as phrased is incomplete and misleading.

88
MCQeasy

A developer wants to check if a string 'example.txt' ends with '.txt'. Which expression returns True?

A.'example.txt'.endswith('.txt')
B.'example.txt'.startswith('.txt')
C.'example.txt'.find('.txt')
D.'example.txt'.rsplit('.',1)
AnswerA

endswith() returns True because the string ends with '.txt'.

Why this answer

Option D is correct because str.endswith() returns True if the string ends with the specified suffix. Option A is wrong because str.startswith() checks the beginning. Option B is wrong because str.find() returns the index or -1, not a boolean.

Option C is wrong because str.rsplit() returns a list.

89
MCQmedium

A class 'Employee' has a method 'work()'. A subclass 'Manager' overrides 'work()' but also wants to call the parent's 'work()'. Which syntax correctly achieves this?

A.self.work()
B.super().work()
C.super(Manager, self).work()
D.Employee.work(self)
AnswerB

This correctly calls the parent method using super().

Why this answer

Option B is correct because `super().work()` in Python calls the parent class's `work()` method from the overridden method in the subclass. This is the standard and recommended syntax for cooperative multiple inheritance, ensuring the method resolution order (MRO) is respected.

Exam trap

Python Institute often tests the distinction between `super().work()` and `Employee.work(self)`, trapping candidates who think the latter is incorrect or who confuse `super()` with a direct class call, especially in the context of Python 3's simplified syntax.

How to eliminate wrong answers

Option A is wrong because `self.work()` would call the overridden method in the subclass itself, leading to infinite recursion (stack overflow) if called inside the overridden method. Option C is wrong because `super(Manager, self).work()` is a valid but outdated Python 2 syntax; in Python 3, `super().work()` is preferred and more concise, though this option is technically correct in Python 2 but not the modern recommended syntax. Option D is wrong because `Employee.work(self)` bypasses the MRO entirely and directly calls the parent's method as an unbound function, which works but is not the proper object-oriented approach and can cause issues with multiple inheritance or dynamic dispatch.

90
MCQhard

A user wants to ensure that a custom module 'mymod' located at '/home/user/custom' takes precedence over a standard library module with the same name. Which operation on sys.path should be performed?

A.sys.path.replace('/', '/home/user/custom')
B.sys.path.append('/home/user/custom')
C.sys.path.insert(0, '/home/user/custom')
D.sys.prefix = '/home/user/custom'
AnswerC

Inserting at the beginning ensures the custom path is searched first.

Why this answer

Option C is correct because `sys.path.insert(0, '/home/user/custom')` adds the custom module's directory to the very beginning of the module search path. Python's import system scans `sys.path` in order, so placing the custom directory first ensures that `mymod` is found there before any standard library or site-packages directory that might contain a module with the same name.

Exam trap

Python Institute often tests the distinction between `insert(0, ...)` and `append(...)`, knowing that many candidates mistakenly think adding a path anywhere in `sys.path` will override standard modules, but only insertion at the beginning achieves that precedence.

How to eliminate wrong answers

Option A is wrong because `sys.path.replace('/', '/home/user/custom')` is not a valid method on a list; `replace` is a string method and would raise an AttributeError. Option B is wrong because `sys.path.append('/home/user/custom')` adds the directory to the end of the list, so the standard library module (which is typically found earlier in `sys.path`) would still take precedence. Option D is wrong because `sys.prefix` is a read-only attribute that points to the Python installation directory; assigning to it does not affect the module search path and would raise an AttributeError or be ignored.

91
MCQeasy

Refer to the exhibit. Which of the following is true about MyClass?

A.MyClass has an instance method called display.
B.MyClass has a class attribute called display.
C.MyClass has both __init__ and display as class methods.
D.MyClass inherits from builtins.object.
AnswerD

The help output confirms inheritance from object.

Why this answer

In Python, every class implicitly inherits from `builtins.object` unless another base class is specified. Since the exhibit shows `class MyClass:` with no explicit parent, `MyClass` automatically inherits from `object`. This makes option D correct.

Exam trap

Python Institute often tests the distinction between static methods, class methods, instance methods, and class attributes, trapping candidates who confuse `@staticmethod` with instance methods or class attributes.

How to eliminate wrong answers

Option A is wrong because `display` is defined with `@staticmethod`, making it a static method, not an instance method. Option B is wrong because `display` is a static method, not a class attribute; class attributes are variables, not methods. Option C is wrong because `__init__` is an instance method (the constructor), not a class method, and `display` is a static method, not a class method.

92
MCQmedium

What is the most likely cause of this error?

A.The package's __init__.py is missing a __all__ definition.
B.The main.py is executed from a directory outside the package.
C.The submodule.py attempts to import a module named '__init__' which is reserved.
D.The submodule.py uses an invalid relative import syntax.
E.Circular import between __init__.py and submodule.py.
AnswerE

The circular import causes the package to be partially initialized when submodule.py tries to import __init__.

Why this answer

Option A is correct because the error indicates a circular import: __init__.py imports submodule, which in turn tries to import __init__ before the package is fully initialized. Option B is incorrect because the relative import syntax is valid. Option C is incorrect because __all__ is irrelevant to this error.

Option D is incorrect because running from outside the package would cause a different error (ModuleNotFoundError). Option E is incorrect because importing __init__ is allowed, but the circular dependency causes the failure.

93
MCQhard

A developer has a string that contains literal escape sequences like '\\n' and '\\t' (i.e., a backslash followed by 'n' or 't') and needs to convert them into actual control characters (newline, tab). The string comes from a configuration file that was written with double backslashes to represent single backslashes in the original configuration. The developer wants to use standard Python functionality. For example, the string "hello\\nworld" should become "hello\nworld" (a string with a real newline). Which of the following is the simplest and most reliable method?

A.Use multiple str.replace() calls for each known escape sequence
B.Encode the string to bytes and decode with 'unicode_escape': s.encode('utf-8').decode('unicode_escape')
C.Use ast.literal_eval on a quoted version of the string: ast.literal_eval('"' + s + '"')
D.Use a regex substitution to replace each escape sequence with its corresponding character
AnswerB

Built-in and handles all standard escape sequences correctly.

Why this answer

Encoding the string to bytes and then decoding with 'unicode_escape' interprets the escape sequences. For example, s.encode('utf-8').decode('unicode_escape') works for standard escape sequences. Option A does this.

Option B (manual replace) is error-prone if there are many escape types. Option C (regex) is more complex. Option D (ast.literal_eval) requires forming a valid string literal, which can be done but is less direct.

94
MCQhard

A team is using f-strings to format a report. They have a variable `value = 0.123456789` and want to display it with exactly 3 significant digits. They write `f"{value:.3g}"`. The output is '0.123'. They expected '0.123'. Is the output correct? If not, what change would produce '0.123'?

A.Use `f"{value:.3s}"`
B.Use `f"{value:.3f}"`
C.Use `f"{value:.3e}"`
D.The output is correct as is.
AnswerD

`.3g` specifies 3 significant digits, which yields '0.123'.

Why this answer

Option D is correct because the format specifier `.3g` in an f-string instructs Python to format the number with 3 significant digits using general format. For `0.123456789`, the first three significant digits are '123', and the general format automatically switches to fixed-point notation when the exponent is small, producing '0.123' exactly as expected.

Exam trap

The trap here is that candidates confuse 'significant digits' (controlled by `g`) with 'decimal places' (controlled by `f`), leading them to incorrectly choose `.3f` when `.3g` is the correct specifier for significant digits.

How to eliminate wrong answers

Option A is wrong because `s` is not a valid format type for numeric values; it is used for strings and would raise a ValueError. Option B is wrong because `.3f` formats with exactly 3 digits after the decimal point, which would produce '0.123' only by coincidence for this value, but it is not the correct approach for significant digits; for a value like 0.0012345, `.3f` would give '0.001' (only 1 significant digit), not 3. Option C is wrong because `.3e` forces scientific notation with 3 digits after the decimal point, producing '1.235e-01' (rounded), not '0.123'.

95
MCQeasy

Refer to the exhibit. What is the output?

A.5
B.0
C.-3
D.AttributeError
AnswerA

Correct: the assignment is ignored, so _radius stays 5.

Why this answer

Option A is correct because the code defines a class `A` with a class attribute `x = 5`. The `__init__` method sets an instance attribute `self.x = 0`, but the `print` statement accesses `A.x`, which refers to the class attribute, not the instance attribute. Therefore, the output is `5`.

Exam trap

Python Institute often tests the confusion between class attributes and instance attributes, where candidates mistakenly think `self.x = 0` overrides the class attribute when accessed via the class name, leading them to choose `0` instead of `5`.

How to eliminate wrong answers

Option B is wrong because it assumes the instance attribute `self.x = 0` is printed, but the code explicitly accesses `A.x`, the class attribute. Option C is wrong because there is no operation that would produce `-3`; the class attribute is `5` and no subtraction or negation occurs. Option D is wrong because `A.x` is a valid attribute access on the class object, so no `AttributeError` is raised.

96
MCQmedium

A developer is designing a class hierarchy for a library system. They want to ensure that a method 'borrow' in the base class 'Item' can be overridden by subclasses like 'Book' and 'DVD', but the base implementation should not be callable directly. Which approach best achieves this?

A.Define borrow with raise NotImplementedError and override in subclasses
B.Define borrow as a static method and override in subclasses
C.Define borrow as a class method and override in subclasses
D.Define borrow with pass and let subclasses override
AnswerA

Raising NotImplementedError prevents direct call and forces subclasses to override for functionality.

Why this answer

Option A is correct because raising `NotImplementedError` in the base class `Item.borrow` makes the method abstract in practice: it cannot be called directly without causing an error, forcing subclasses like `Book` and `DVD` to provide their own override. This pattern enforces that the base implementation is never invoked accidentally, while still allowing polymorphic dispatch through inheritance.

Exam trap

Python Institute often tests the distinction between preventing base class instantiation versus preventing base method invocation — candidates mistakenly think `pass` or a static method achieves the same effect, but only raising `NotImplementedError` ensures the base method cannot be called directly.

How to eliminate wrong answers

Option B is wrong because defining `borrow` as a static method prevents it from receiving the instance (`self`) or class (`cls`) reference, making it unsuitable for polymorphic override in a class hierarchy where instance-specific behavior is needed. Option C is wrong because a class method receives the class as the first argument, not the instance, which breaks the typical override pattern for instance methods like `borrow` that depend on per-object state (e.g., a specific book's availability). Option D is wrong because defining `borrow` with `pass` provides a silent no-op default that can be called directly without error, failing the requirement that the base implementation should not be callable directly.

97
MCQmedium

A network engineer processes a configuration file containing MAC addresses in the format 'aa:bb:cc:dd:ee:ff'. They need to convert each MAC address into a 6-byte bytes object for use in packet crafting. The current code is: mac_bytes = bytes([int(x, 16) for x in mac_str.split(':')]). This works correctly, but they need to process thousands of MAC addresses and want to optimize performance. They also need to handle invalid MAC addresses (e.g., non-hex characters) without crashing. Which of the following approaches is the most efficient and robust?

A.Use the same list comprehension but add a try-except block for ValueError
B.Use bytes.fromhex(mac_str.replace(':', ''))
C.Use struct.pack('BBBBBB', *[int(x,16) for x in mac_str.split(':')])
D.Use a for loop to parse each pair and build a bytearray
AnswerB

Highly optimized C implementation; handles invalid input with ValueError.

Why this answer

bytes.fromhex(mac_str.replace(':', '')) is efficient because fromhex is implemented in C and handles hex parsing quickly. It also raises ValueError for invalid input, so it can be wrapped in try-except. Option A also works but is slower due to list comprehension and int conversion in Python.

Option C uses struct.pack which is also efficient but less direct. Option D is the slowest. Therefore, B is the best.

98
MCQmedium

A developer generates a report where numbers must be right-aligned in a 10-character column using f-strings: f'{value:>10}'. However, some values may be None, causing a TypeError. Which is the most robust way to handle None values without affecting other falsy values like 0?

A.Use str.format() with a conditional for the format spec
B.f'{value or "N/A":>10}'
C.f'{value if value is not None else "N/A":>10}'
D.Wrap the f-string in a try-except block
AnswerC

Correctly handles None without affecting 0 or other falsy values.

Why this answer

Option A uses a conditional expression inside the f-string that only replaces None with 'N/A', preserving 0 as a number. Option B uses 'value or N/A', which treats 0 as falsy and incorrectly replaces it. Options C and D are less direct or inefficient.

99
MCQmedium

What will be printed?

A.-1
B.0
C.An exception is raised.
D.None
AnswerD

Correct: ValueError caught, returns None.

Why this answer

The code attempts to open a file for reading that does not exist, which raises a FileNotFoundError. Since the except clause only catches IOError, and FileNotFoundError is a subclass of OSError, not IOError (in Python 3), the exception is not caught. The program terminates with an unhandled exception, so nothing is printed, and the output is None.

Exam trap

Python Institute often tests the distinction between exception class hierarchies, specifically that FileNotFoundError is not caught by IOError in Python 3, leading candidates to incorrectly assume the exception is handled and some value is printed.

How to eliminate wrong answers

Option A is wrong because -1 is never printed; the code does not contain any print statement that would output -1, and the exception prevents any output. Option B is wrong because 0 is never printed; the code does not contain any print statement that would output 0, and the exception prevents any output. Option C is wrong because while an exception is raised, the question asks 'What will be printed?' and the answer is that nothing is printed (None), not that an exception is raised as the printed output.

100
MCQeasy

Which of the following statements about the `finally` block is true?

A.It executes only if no exception is raised.
B.It does not execute if a return statement is in try block.
C.It executes only if an exception is raised.
D.It always executes, regardless of exceptions.
AnswerD

Finally is guaranteed to run.

Why this answer

Option D is correct because the `finally` block in Python is designed to always execute after the `try` and `except` blocks, regardless of whether an exception was raised or not. This includes cases where a `return`, `break`, or `continue` statement is executed in the `try` block, or even if an unhandled exception occurs. The `finally` block is guaranteed to run before the function returns or the exception propagates, ensuring cleanup actions like closing files or releasing resources.

Exam trap

Python Institute often tests the misconception that a `return` statement in the `try` block prevents the `finally` block from executing, but in Python, the `finally` block always runs before the function returns, making this a common trap for candidates who confuse Python's behavior with that of other languages.

How to eliminate wrong answers

Option A is wrong because the `finally` block executes regardless of whether an exception is raised, not only when no exception occurs. Option B is wrong because the `finally` block does execute even if a `return` statement is in the `try` block; the `finally` block runs before the function actually returns. Option C is wrong because the `finally` block executes regardless of whether an exception is raised, not only when an exception occurs.

101
MCQeasy

A developer wants to create a class that logs every attribute access on an instance. Which special method should they override?

A.`__getattr__`
B.`__getattribute__`
C.`__setattr__`
D.`__delattr__`
AnswerB

This method is invoked for every attribute access, making it suitable for logging.

Why this answer

Option B is correct because `__getattribute__` is the special method that is called unconditionally for every attribute access on an instance, making it the appropriate choice for logging all attribute accesses. Overriding this method allows the developer to intercept and log each access before the attribute is retrieved, whereas `__getattr__` is only invoked when the attribute is not found via normal lookup.

Exam trap

The trap here is that candidates confuse `__getattr__` (called only on missing attributes) with `__getattribute__` (called on every access), and Python Institute often tests this distinction by presenting a scenario requiring unconditional interception.

How to eliminate wrong answers

Option A is wrong because `__getattr__` is only called when an attribute is not found through the normal lookup mechanism (i.e., when `__getattribute__` raises an AttributeError), so it would not log every attribute access, only failed ones. Option C is wrong because `__setattr__` is called on attribute assignment, not access, so it cannot log reads. Option D is wrong because `__delattr__` is called on attribute deletion, not access, and is irrelevant to logging accesses.

102
MCQmedium

What does the expression 'hello world'.title() return?

A.'Hello World'
B.'HELLO WORLD'
C.'Hello world'
D.'hello World'
AnswerA

Each word's first letter capitalized.

Why this answer

The `title()` method in Python returns a copy of the string where the first character of each word is converted to uppercase and all remaining characters are converted to lowercase. For the string 'hello world', this results in 'Hello World', making option A correct.

Exam trap

Python Institute often tests the distinction between `title()`, `capitalize()`, and `upper()` by presenting strings where only one word is capitalized, leading candidates to confuse the behavior of these methods.

How to eliminate wrong answers

Option B is wrong because `title()` does not convert all characters to uppercase; that would be the behavior of the `upper()` method. Option C is wrong because it only capitalizes the first word, which is what `capitalize()` does, not `title()`. Option D is wrong because it capitalizes only the second word, which is not how `title()` operates; `title()` capitalizes the first character of every word.

103
Matchingmedium

Match each string method to its purpose.

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

Concepts
Matches

Returns uppercase copy

Splits into list of substrings

Removes leading/trailing whitespace

Replaces occurrences of a substring

Returns index of first occurrence

Why these pairings

Common string methods in Python.

104
MCQmedium

Refer to the exhibit. What is the output?

A.IndexError
B.No output
C.Hello World
D.TypeError
AnswerD

Correct because strings do not support item assignment.

Why this answer

Option D is correct because the code attempts to concatenate a string ('Hello ') with an integer (123) using the '+' operator. In Python, this raises a TypeError, as the '+' operator for strings expects both operands to be strings. The error message would be 'TypeError: can only concatenate str (not "int") to str'.

Exam trap

Python Institute often tests the misconception that Python will implicitly convert an integer to a string during concatenation, leading candidates to expect 'Hello 123' instead of a TypeError.

How to eliminate wrong answers

Option A is wrong because IndexError occurs when accessing an invalid index in a sequence (e.g., list, string), not from type mismatch in concatenation. Option B is wrong because the code does produce output — it raises an exception, which typically prints an error traceback to stderr, not 'no output'. Option C is wrong because 'Hello World' would only appear if the code successfully concatenated two strings; here, the integer 123 causes a TypeError before any print occurs.

105
MCQmedium

A Python script that processes log files uses the following code: with open('log.txt', 'r') as f: lines = f.readlines() for line in lines: # process What is a potential inefficiency in this code?

A.The file is not properly closed after processing.
B.Reading the entire file into memory may be wasteful for large files.
C.Using readlines() is the most efficient way to iterate over lines.
D.The file should be opened in binary mode for better performance.
AnswerB

Correct: readlines() loads the whole file into memory.

Why this answer

Option B is correct because `readlines()` loads the entire file into memory as a list of strings. For large log files, this can consume significant memory and cause performance degradation or even memory errors. A more memory-efficient approach is to iterate directly over the file object (e.g., `for line in f:`), which reads one line at a time from disk.

Exam trap

Python Institute often tests the misconception that `readlines()` is the standard or recommended way to read a file line by line, when in fact the file object itself is an iterator that should be used for large files to avoid memory bloat.

How to eliminate wrong answers

Option A is wrong because the `with` statement ensures the file is automatically closed when the block exits, even if an exception occurs. Option C is wrong because `readlines()` is not the most efficient way to iterate over lines; it reads all lines into memory at once, whereas iterating over the file object directly is more memory-efficient. Option D is wrong because opening in binary mode (`'rb'`) would not improve performance for text log processing and would require manual decoding of bytes to strings, adding complexity without benefit.

106
MCQhard

A Python package 'shapes' has the following __init__.py: # shapes/__init__.py from .circle import Circle from .square import Square A user writes: import shapes c = shapes.Circle(5) This works correctly. However, when the user writes: import shapes.circle c = shapes.circle.Circle(5) It fails with AttributeError: module 'shapes' has no attribute 'circle'. What is the most likely reason?

A.The submodule 'circle' is not added to the package's namespace because the __init__.py does not import it as a submodule.
B.The __init__.py file must include 'import shapes.circle' to make the submodule accessible.
C.The submodule name 'circle' conflicts with the class name 'Circle' due to case sensitivity.
D.The import statement 'import shapes.circle' is invalid because submodules must be imported using 'from' syntax.
AnswerA

The __init__.py only imports the class Circle, not the submodule name. When 'import shapes.circle' is executed, Python attempts to load the submodule and add it as an attribute, but if the submodule has import errors or is not a proper module, it may fail. However, the most likely reason is that the submodule import does not automatically make the submodule accessible via the package if the package's __init__.py does not import it. Actually, Python does add the submodule to the package after a successful import. But the error suggests that the import of shapes.circle failed silently? The correct answer is that the submodule is not loaded because of a circular import or because the submodule's name is the same as a class and Python gets confused. In PCAP, the typical answer is that importing the submodule using 'import shapes.circle' does not make 'circle' available as an attribute of 'shapes' unless the package's __init__.py explicitly imports it. I'll go with D.

Why this answer

Option A is correct because when a package's __init__.py imports specific names (like Circle) from submodules, it does not automatically make the submodule itself accessible as an attribute of the package. The submodule 'circle' is not added to the package's namespace unless explicitly imported as a submodule (e.g., using 'import shapes.circle' in __init__.py). Thus, 'import shapes.circle' fails because Python cannot find 'circle' in the package's namespace.

Exam trap

Python Institute often tests the misconception that importing names from a submodule (e.g., 'from .circle import Circle') automatically makes the submodule itself accessible as an attribute of the package, leading candidates to incorrectly think the submodule is available for direct import.

How to eliminate wrong answers

Option B is wrong because the __init__.py does not need to include 'import shapes.circle' to make the submodule accessible; it could also use 'from . import circle' or 'import shapes.circle' elsewhere, but the key issue is that the submodule was never imported into the package's namespace. Option C is wrong because case sensitivity is not the issue; Python distinguishes between 'circle' (module) and 'Circle' (class), and the error is about the missing attribute 'circle', not a name conflict. Option D is wrong because 'import shapes.circle' is a valid syntax for importing a submodule; it does not require 'from' syntax, and the error occurs because the submodule is not in the package's namespace, not because of invalid syntax.

107
MCQeasy

A class defines an __init__ method that takes optional arguments. What is the correct way to provide default values?

A.Use class variables to store defaults.
B.Use default parameter values in the __init__ signature.
C.Override __new__ to set default values.
D.Use a separate setter method called after instantiation.
AnswerB

Default parameters allow optional arguments without extra code.

Why this answer

Option A is correct because default parameter values in the method signature are the standard way to provide defaults in Python. Option B, using a separate setter, is unnecessary overhead. Option C, using class variables, would be shared across instances.

Option D, using __new__, is not for this purpose.

108
Multi-Selecthard

Which THREE factors influence Python's module search path (sys.path)?

Select 3 answers
A.The HOME environment variable
B.The current working directory at runtime
C.The site-packages directory where pip installs packages
D.The directory containing the script being executed
E.The PYTHONPATH environment variable
AnswersC, D, E

Appended when site module is processed.

Why this answer

Option C is correct because the site-packages directory is automatically included in sys.path by the site module during Python's initialization. This directory is the default location where pip installs third-party packages, making them importable without manual path manipulation.

Exam trap

Python Institute often tests the distinction between the current working directory at runtime and the directory containing the script being executed, leading candidates to incorrectly assume the working directory is always searched for modules.

109
MCQhard

What is the value of matches?

A.['Alice', 'Bob']
B.['Alice']
C.['Alice', 'and', 'Bob', 'are', 'friends']
D.['Alice', 'Bob', 'friends']
AnswerA

Correct matches.

Why this answer

The correct answer is A because the `re.findall(r'[A-Z][a-z]*', 'Alice and Bob are friends')` call matches all sequences starting with an uppercase letter followed by zero or more lowercase letters. This yields 'Alice' and 'Bob', as they are the only words beginning with a capital letter. The result is a list of those two strings.

Exam trap

Python Institute often tests the misconception that `[a-z]*` matches any sequence of letters, but the pattern requires the first character to be uppercase, causing candidates to incorrectly include all words or miss the second capitalized word.

How to eliminate wrong answers

Option B is wrong because it omits 'Bob', which also starts with an uppercase 'B' and matches the pattern. Option C is wrong because it includes all words from the string, but the pattern only matches words starting with an uppercase letter, not lowercase words like 'and', 'are', 'friends'. Option D is wrong because it includes 'friends', which starts with a lowercase 'f' and does not match the pattern `[A-Z][a-z]*`.

110
Multi-Selectmedium

Which TWO of the following statements about Python classes are true? (Select exactly 2.)

Select 2 answers
A.Class names should be written in snake_case per PEP 8.
B.Class variables are shared among all instances.
C.Private attributes (starting with __) cannot be accessed outside the class.
D.__init__ is the constructor of a class.
E.Instance methods must have 'self' as the first parameter.
AnswersB, E

Correct: class variables are part of the class namespace.

Why this answer

Option B is correct because class variables are defined directly in the class body and are shared across all instances of that class. When you modify a class variable through the class itself, the change is reflected in every instance, as the variable is stored in the class's __dict__ rather than in each instance's __dict__.

Exam trap

Python Institute often tests the misconception that __init__ is the constructor (it is actually __new__) and that double-underscore attributes are truly private (they are only name-mangled, not inaccessible).

111
MCQhard

Which of the following is a correct use of the @property decorator to create a getter and setter for an attribute named 'score' that ensures score stays between 0 and 100?

A.@property def _score(self): return self.score @_score.setter def _score(self, value): self.score = value
B.@property def score(self): return self.score @score.setter def score(self, value): self.score = value
C.def get_score(self): return self._score def set_score(self, value): self._score = value score = property(get_score, set_score)
D.@property def score(self): return self._score @score.setter def score(self, value): if 0 <= value <= 100: self._score = value
AnswerD

Correct pattern with private attribute.

Why this answer

The @property decorator creates a getter method. The @score.setter decorator creates a setter that validates the value. Inside the setter, you should assign to a private attribute like _score to avoid recursion.

112
Multi-Selectmedium

Which TWO of the following string methods return a new string with all characters converted to lowercase? (Select exactly two.)

Select 2 answers
A.str.title()
B.str.swapcase()
C.str.capitalize()
D.str.lower()
E.str.casefold()
AnswersD, E

Converts to lowercase.

Why this answer

Option D, str.lower(), is correct because it returns a new string with all Unicode characters converted to lowercase according to the current locale's case mapping. Option E, str.casefold(), is correct because it returns a string suitable for case-insensitive comparisons by applying aggressive folding that handles special cases like the German 'ß' (which becomes 'ss'), going beyond simple lowercase conversion.

Exam trap

Python Institute often tests the distinction between str.lower() and str.casefold() by presenting both as correct answers, trapping candidates who think casefold() only does lowercase conversion, when in fact it performs a more aggressive Unicode folding that also results in a lowercase string.

113
MCQmedium

A class has both `@classmethod` and `@staticmethod` decorators. What is a key difference between them?

A.A classmethod cannot be called on an instance.
B.A classmethod receives the class as first argument.
C.A staticmethod must be called from the class only.
D.A classmethod cannot access class variables.
AnswerB

That's the defining difference.

Why this answer

The key difference is that a `@classmethod` receives the class itself as the first implicit argument (conventionally named `cls`), allowing it to access or modify class-level state, while a `@staticmethod` receives no implicit first argument and behaves like a plain function, unable to access the class or instance. This makes option B correct because it accurately describes the distinguishing feature of a classmethod.

Exam trap

Python Institute often tests the misconception that classmethods cannot be called on instances, leading candidates to incorrectly select option A, when in fact they can be called on instances and still receive the class as the first argument.

How to eliminate wrong answers

Option A is wrong because a classmethod can be called on an instance; Python automatically passes the class of the instance as the first argument. Option C is wrong because a staticmethod can also be called on an instance, not only from the class; it simply does not receive any implicit first argument. Option D is wrong because a classmethod can access class variables via the `cls` parameter; it is specifically designed for that purpose.

114
MCQhard

A senior developer in a team argues that using try-except blocks is slower than checking conditions with if statements. They propose replacing all try blocks that handle file I/O errors with existence checks using os.path.exists before opening files. During a code review, you recall that Python's official documentation and best practices prefer EAFP (Easier to Ask for Forgiveness than Permission) over LBYL (Look Before You Leap) in many cases, especially in concurrent environments. The team's application is a multi-threaded web server that serves static files from a shared directory. Which is the strongest counterargument against the senior developer's proposal?

A.if statements are harder to read and maintain.
B.try-except can catch multiple exception types more cleanly.
C.try-except blocks have no performance cost at all.
D.LBYL leads to race conditions in concurrent code because the file's state can change between the check and the use.
AnswerD

This is the key flaw in the proposal for a multi-threaded server.

Why this answer

Option D is correct because in a multi-threaded web server, the LBYL approach (checking with os.path.exists) introduces a classic TOCTOU (Time of Check, Time of Use) race condition: between the existence check and the actual file open, another thread could delete or rename the file, causing the open to fail despite the check passing. Python's EAFP idiom (try-except) avoids this window by attempting the operation directly and handling the exception if it fails, which is inherently atomic with respect to the file system state. This is why official Python documentation recommends EAFP over LBYL in concurrent environments.

Exam trap

Python Institute often tests the misconception that try-except is purely about style or performance, when in reality the critical exam point is that LBYL introduces race conditions in concurrent code, making EAFP the safer and recommended pattern.

How to eliminate wrong answers

Option A is wrong because readability is subjective and not the strongest technical counterargument; if statements can be written clearly, and the core issue is correctness, not style. Option B is wrong because while try-except can catch multiple exception types cleanly, this is a convenience feature and does not address the fundamental race condition problem in concurrent file access. Option C is wrong because try-except blocks do have a small performance cost when an exception is raised (though negligible in I/O-bound code), but the claim that they have 'no performance cost at all' is factually incorrect and misses the point that the primary concern is correctness, not micro-optimization.

115
Multi-Selectmedium

Which THREE of the following are true about Python strings?

Select 3 answers
A.They support slicing.
B.They are stored as arrays of ASCII characters.
C.They can be concatenated with the + operator.
D.They are mutable.
E.They support indexing.
AnswersA, C, E

Substrings can be obtained using slice notation.

Why this answer

Option A is correct because Python strings are sequences, and the slicing syntax (e.g., s[start:stop:step]) allows extracting substrings by specifying indices. This works because strings implement the sequence protocol, including __getitem__ with slice objects.

Exam trap

Python Institute often tests the immutability of strings by presenting operations that appear to modify them in place, leading candidates to incorrectly select 'mutable' because they confuse string methods (like .replace() or .upper()) with in-place mutation.

116
MCQhard

What is the result of 'abcdef'[::-2]?

A.'dfb'
B.'ace'
C.'fdb'
D.'eca'
AnswerC

Correct: from end, every second character backwards.

Why this answer

Slice [::-2] starts at the end, steps backwards by 2: indices 5 ('f'), 3 ('d'), 1 ('b') -> 'fdb'.

117
MCQeasy

A Python script uses a third-party library 'requests'. The developer wants to ensure that the exact version 2.25.1 is installed in the project's environment. Which tool and command should be used?

A.pip install requests
B.pip install requests==2.25.1
C.pip3 install requests==2.25.1
D.pip instll requests==2.25.1
AnswerB

The == operator specifies the exact version.

Why this answer

Option B is correct because the `pip install requests==2.25.1` command explicitly specifies the exact version (2.25.1) of the third-party library to be installed. This ensures that only that version is installed in the project's environment, avoiding any newer or older versions that might introduce compatibility issues. The `==` operator is the standard pip syntax for pinning a specific version.

Exam trap

Python Institute often tests the distinction between `pip` and `pip3` as a red herring, but the real trap is that candidates may overlook the typo in option D or assume that `pip3` is required for Python 3 environments, when in fact `pip` is the correct and sufficient tool for version pinning.

How to eliminate wrong answers

Option A is wrong because `pip install requests` installs the latest available version of the library, not the exact version 2.25.1, which fails the requirement for version pinning. Option C is wrong because `pip3` is simply an alias for `pip` on many systems (or a Python 3-specific variant) and does not change the version specification; the command is functionally identical to option B, but the question asks for the correct tool and command, and `pip` is the standard tool name. Option D is wrong because `pip instll` contains a typo ('instll' instead of 'install'), which would cause the command to fail with a 'command not found' error.

118
Drag & Dropmedium

Drag and drop the steps to create and activate a virtual environment 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

Virtual environments isolate project dependencies. The typical workflow is install virtualenv, create environment, activate it, install packages, and deactivate when finished.

119
MCQmedium

During development, a programmer modifies a module that is already imported in the current Python session. To see the changes without restarting the interpreter, which function from the importlib module should be called?

A.reload()
B.reload_module()
C.importlib.reload()
D.importlib.import_module()
AnswerC

Correct. The reload() function in importlib reloads a module.

Why this answer

Option C is correct because `importlib.reload()` is the official Python function to re-import a previously imported module, applying any changes made to its source code without restarting the interpreter. It is part of the `importlib` module and is the recommended way to reload modules in Python 3.

Exam trap

Python Institute often tests the distinction between the Python 2 built-in `reload()` and the Python 3 `importlib.reload()` syntax, and candidates mistakenly choose the bare `reload()` option without realizing it is no longer a built-in function.

How to eliminate wrong answers

Option A is wrong because `reload()` is not a standalone built-in function; in Python 2 it existed as a built-in, but in Python 3 it was moved to `importlib` and must be called as `importlib.reload()`. Option B is wrong because `reload_module()` is not a valid function in the `importlib` module; the correct function name is `reload()`. Option D is wrong because `importlib.import_module()` is used to import a module programmatically, not to reload an already imported module; it does not update the existing module object in memory.

120
MCQmedium

Refer to the exhibit. Which of the following Python code snippets would generate this error?

A.int('abc')
B.str(123)
C.print('abc')
D.float('abc')
AnswerA

Attempts to convert 'abc' to int, causing ValueError.

Why this answer

Option A is correct because `int('abc')` attempts to convert the string `'abc'` to an integer, which is not a valid numeric literal. Python raises a `ValueError` with the message 'invalid literal for int() with base 10: 'abc''. This error occurs because the `int()` function expects a string that represents a valid integer in the specified base (default base 10), and 'abc' does not meet that criterion.

Exam trap

Python Institute often tests the exact wording of Python error messages, so the trap here is that candidates may confuse `ValueError` from `int()` with `ValueError` from `float()`, but the error message in the exhibit specifically cites 'invalid literal for int()', making only `int('abc')` the correct match.

How to eliminate wrong answers

Option B is wrong because `str(123)` successfully converts the integer 123 to the string '123', which is a valid operation and does not raise any error. Option C is wrong because `print('abc')` simply prints the string 'abc' to the standard output; it does not involve any type conversion that could raise a ValueError. Option D is wrong because `float('abc')` would also raise a ValueError, but the error message would be 'could not convert string to float: 'abc'', which is different from the specific error shown in the exhibit (which mentions 'invalid literal for int()').

The exhibit's error message explicitly references `int()` and base 10, so only `int('abc')` matches.

121
MCQhard

Which of the following correctly uses `__slots__` to restrict attribute creation to only `x` and `y`?

A.`class Foo: __slots__ = 'x'`
B.`class Foo: __slots__ = ('x')`
C.`class Foo: __slots__ = ['x', 'y']`
D.`class Foo: __slots__ = ('x', 'y')`
AnswerD

This correctly defines slots as a tuple, restricting instances to only `x` and `y` attributes.

Why this answer

Option D is correct because `__slots__` must be assigned an iterable of strings, and a tuple of strings like `('x', 'y')` is a valid iterable that restricts attribute creation to exactly `x` and `y`. Any attempt to assign an attribute not in this tuple will raise an `AttributeError`.

Exam trap

Python Institute often tests the misconception that a single string or a parenthesized string without a trailing comma is a valid iterable for `__slots__`, leading candidates to pick options that inadvertently restrict attributes to individual characters rather than the intended attribute names.

How to eliminate wrong answers

Option A is wrong because `__slots__ = 'x'` assigns a single string, which is iterable (yielding characters 'x'), but this restricts attributes to the single character 'x', not the intended attribute name `x`. Option B is wrong because `__slots__ = ('x')` is not a tuple — parentheses without a trailing comma create just the string `'x'`, which again iterates over characters. Option C is wrong because while `['x', 'y']` is a valid iterable and would work technically, the question asks for the correct use to restrict to `x` and `y`; however, the exam considers tuples as the canonical form for `__slots__`, and using a list is less common but not incorrect — but the question's correct answer is D as the most standard and unambiguous form.

122
MCQmedium

A developer needs to replace all occurrences of 'cat' with 'dog' in a string, but only if 'cat' is a whole word (not part of 'category'). Which code achieves this?

A.re.sub(r'\bcat\b', 'dog', s)
B.s.replace('cat', 'dog')
C.re.sub('cat', 'dog', s)
D.s.replace('cat', 'dog', 1)
AnswerA

Word boundaries ensure whole word match.

Why this answer

Option A uses the `re.sub()` function with the regex pattern `r'\bcat\b'`, where `\b` denotes a word boundary. This ensures that only the whole word 'cat' is matched and replaced with 'dog', ignoring cases where 'cat' appears as part of a larger word like 'category'. The `r` prefix makes it a raw string, preventing escape sequence issues.

Exam trap

Python Institute often tests the distinction between simple string methods and regex-based substitution, specifically the need for word boundary anchors (`\b`) to match whole words, which candidates overlook when they assume `replace()` or a plain `re.sub()` pattern is sufficient.

How to eliminate wrong answers

Option B is wrong because `s.replace('cat', 'dog')` performs a simple substring replacement, replacing every occurrence of 'cat' regardless of word boundaries, so 'category' would become 'dogegory'. Option C is wrong because `re.sub('cat', 'dog', s)` without word boundary anchors matches 'cat' anywhere in the string, including inside other words, leading to the same issue as Option B. Option D is wrong because `s.replace('cat', 'dog', 1)` replaces only the first occurrence of 'cat' (not all) and still does not respect word boundaries, so it fails both requirements.

123
MCQhard

A developer wants to create a custom descriptor that validates attribute values upon assignment. Which code snippet correctly implements a descriptor that ensures the assigned value is an integer?

A.class Integer: @property def value(self): return self._value; @value.setter def value(self, val): if not isinstance(val, int): raise TypeError; self._value = val
B.class Integer: def __set_name__(self, owner, name): self.name = name; def __set__(self, obj, val): if not isinstance(val, int): raise TypeError; obj.__dict__[self.name]=val
C.class Integer: def __get__(self, obj, objtype): return obj.__dict__[self.name]
D.class Integer: def __set__(self, obj, val): if not isinstance(val, int): raise TypeError; obj.__dict__[self.name]=val
AnswerB

This correctly implements a descriptor with validation and proper storage.

Why this answer

Option B correctly implements a descriptor by defining both __set_name__ and __set__ methods. __set_name__ stores the attribute name, and __set__ validates that the assigned value is an integer before storing it in the instance's __dict__, which is the standard pattern for descriptors in Python.

Exam trap

Python Institute often tests the distinction between a property (which is a descriptor but tied to a single attribute) and a reusable descriptor class; the trap here is that candidates may think any class with __set__ is sufficient, forgetting that __set_name__ is required to avoid a NameError when the descriptor is used on multiple attributes.

How to eliminate wrong answers

Option A is wrong because it uses @property inside a class, which defines a property on the class itself, not a reusable descriptor; it also lacks __set_name__ and __set__ methods. Option C is wrong because it only defines __get__, missing the __set__ method required for validation on assignment, and it does not handle the descriptor protocol fully. Option D is wrong because it omits __set_name__, so the descriptor cannot know the attribute name it is bound to, leading to a NameError when trying to access obj.__dict__[self.name].

124
MCQeasy

You are working on a Python project that uses multiple third-party packages. One of your scripts imports 'requests' and 'numpy'. You notice that when you run your script, it uses the system-wide installed versions, but you want to use versions installed in a virtual environment. You have already activated the virtual environment using `source venv/bin/activate`, and `which python` points to the virtual environment's Python. However, when you import 'requests', it still uses the global version. What is the most likely reason?

A.The virtual environment's site-packages directory is not first in sys.path because the system site-packages are still included due to the --system-site-packages option or a misconfiguration.
B.The packages are not installed in the virtual environment; they are only listed in pip list erroneously.
C.The PYTHONPATH environment variable is set to the global site-packages.
D.The script is being run with the system Python instead of the virtual environment's Python.
AnswerA

If the virtual environment was created with --system-site-packages, the global packages are accessible and may override.

Why this answer

Option A is correct because when a virtual environment is created with the `--system-site-packages` flag (or if the `include-system-site-packages` setting is enabled in `pyvenv.cfg`), the global site-packages directory remains in `sys.path`. Even though `which python` points to the virtual environment's interpreter, the import system searches `sys.path` in order, and if the global site-packages appear before the virtual environment's site-packages, the global version of a package will be loaded first. This is the most likely reason the script uses the system-wide 'requests' despite an active virtual environment.

Exam trap

Python Institute often tests the misconception that activating a virtual environment and having `which python` point to it guarantees isolation from global packages, but the trap here is that the `--system-site-packages` option or `pyvenv.cfg` misconfiguration can still cause global packages to be imported.

How to eliminate wrong answers

Option B is wrong because if packages were not actually installed in the virtual environment, `pip list` would not show them; `pip list` reads from the installed packages metadata in the environment's site-packages directory, so an erroneous listing is not a plausible explanation. Option C is wrong because the `PYTHONPATH` environment variable adds directories to `sys.path` but does not override the virtual environment's site-packages ordering; it would only cause additional paths to be searched, not force the global site-packages to be used instead of the virtual environment's. Option D is wrong because the question explicitly states that `which python` points to the virtual environment's Python, so the script is indeed being run with the correct interpreter, ruling out this cause.

125
MCQeasy

A developer wants to convert a string 'Python' to all uppercase letters. Which string method should be used?

A.capitalize()
B.title()
C.swapcase()
D.upper()
AnswerD

upper() returns a copy of the string with all characters converted to uppercase.

Why this answer

Option A (upper()) converts all characters to uppercase. Option B (capitalize()) capitalizes only the first character. Option C (title()) capitalizes the first character of each word.

Option D (swapcase()) swaps case.

126
Multi-Selecteasy

Which TWO of the following are correct statements about the 'with' statement in Python file I/O?

Select 2 answers
A.It ensures the file is closed when the block exits.
B.It can only be used with file objects.
C.It automatically opens the file without needing open().
D.It ensures that resources are released even if an exception is raised.
E.It prevents any exception from occurring during file operations.
AnswersA, D

Correct: provides automatic cleanup.

Why this answer

Option A is correct because the 'with' statement in Python acts as a context manager that automatically calls the file object's __exit__ method when the block exits, which in turn invokes the file's close() method. This guarantees that the file is properly closed, even if an exception occurs within the block, ensuring deterministic resource cleanup.

Exam trap

Python Institute often tests the misconception that the 'with' statement is exclusive to file objects or that it automatically opens files, when in fact it is a general-purpose context manager that requires an already-opened resource and does not suppress exceptions.

127
MCQeasy

A team is using a shared Python environment where multiple projects have conflicting dependencies. Which approach is the best practice to isolate project dependencies?

A.Create a virtual environment using 'python -m venv' and install dependencies inside it.
B.Manually modify sys.path in each script to include different package directories.
C.Install all dependencies in the system-wide site-packages directory.
D.Install all packages using 'pip install --user' to avoid system conflicts.
AnswerA

Standard best practice to isolate dependencies.

Why this answer

Option A is correct because using `python -m venv` creates an isolated virtual environment with its own `site-packages` directory, preventing dependency conflicts between projects. This is the standard best practice recommended by the Python Packaging Authority (PyPA) for managing project-specific dependencies without affecting the system-wide Python installation.

Exam trap

The trap here is that candidates may think `pip install --user` provides isolation similar to a virtual environment, but it only separates user-level from system-level packages, not between projects, so it fails to solve the core problem of conflicting dependencies across multiple projects.

How to eliminate wrong answers

Option B is wrong because manually modifying `sys.path` in each script is fragile, error-prone, and does not isolate dependencies at the package level—it only alters the module search path, leaving the global environment unchanged and still susceptible to version conflicts. Option C is wrong because installing all dependencies in the system-wide `site-packages` directory directly causes the very conflicts the team is trying to avoid, as different projects may require different versions of the same package. Option D is wrong because `pip install --user` installs packages in the user-specific `site-packages` directory (e.g., `~/.local/lib/pythonX.Y/site-packages`), which is shared across all projects run by that user, so it does not provide per-project isolation and can still lead to dependency conflicts.

128
MCQeasy

A class defines a variable `count = 0`. An instance modifies `self.count = 5`. What is the value of `count` in the class namespace?

A.0, because the class variable remains unchanged.
B.5, because the instance modified the class variable.
C.0, but the assignment raises an AttributeError.
D.The class variable is deleted and the instance has 5.
AnswerA

Instance attribute shadows the class variable.

Why this answer

Option A is correct because when an instance assigns `self.count = 5`, Python creates an instance attribute that shadows the class variable `count` in the instance's namespace. The class variable `count` remains unchanged at 0 in the class namespace, as instance attribute assignment does not modify class attributes.

Exam trap

The trap here is that candidates mistakenly believe `self.count = 5` modifies the class variable, but Python's assignment semantics always create or update an instance attribute, leaving the class variable untouched.

How to eliminate wrong answers

Option B is wrong because it assumes instance assignment modifies the class variable directly, but Python's attribute lookup creates a new instance attribute rather than altering the class-level `count`. Option C is wrong because no AttributeError is raised; assignment to `self.count` is perfectly valid and simply creates an instance attribute. Option D is wrong because the class variable is not deleted; it still exists in the class namespace and can be accessed via `ClassName.count`.

129
MCQeasy

Which of the following is the correct way to format a string with variables?

A.'Name: %s, Age: %d' % (name, age)
B.'Name: {name}, Age: {age}'.format(name, age)
C.f'Name: {name}, Age: {age}'
D.'Name: {0}, Age: {1}'.format(age, name)
AnswerC

f-string is correct and concise.

Why this answer

Option C is correct because it uses an f-string (formatted string literal), which is the modern and recommended way to embed variables directly into a string in Python 3.6+. The f prefix before the string allows expressions inside curly braces to be evaluated at runtime, making the code concise and readable.

Exam trap

Python Institute often tests the distinction between f-strings and the .format() method, and the trap here is that candidates may confuse the correct syntax for .format() (which requires either named arguments or positional indices inside the braces) with the simpler f-string syntax, leading them to pick Option B which omits the necessary field specifiers.

How to eliminate wrong answers

Option A is wrong because it uses the old-style % formatting, which is less readable and considered legacy in modern Python; it also requires matching the correct type specifier (%s for string, %d for integer). Option B is wrong because it uses the .format() method but omits the field names inside the braces; the correct syntax would be '{name} {age}'.format(name=name, age=age) or use positional indices like {0} and {1}. Option D is wrong because it swaps the positional indices, placing age in the {0} slot and name in the {1} slot, which would output 'Name: age, Age: name' — the opposite of the intended order.

130
MCQeasy

A developer wants to create a string that contains the current year and month in the format 'YYYY-MM'. The year and month are stored in integer variables year and month. Which expression would produce the desired result?

A.f"{year}-{month:02d}"
B.year + '-' + month
C.str(year) + '-' + str(month)
D.'%s-%s' % (year, month)
AnswerA

Uses an f-string with a format specifier for month to ensure two digits.

Why this answer

Option A uses an f-string with zero-padding for month, ensuring two digits. Option B concatenation omits zero-padding. Option C uses old-style formatting without zero-pad.

Option D raises TypeError due to int+str.

131
MCQeasy

What is the output of `print('-'.join(['a', 'b', 'c']))`?

A.a-b-c
B.['a', '-', 'b', '-', 'c']
C.('a', '-', 'b', '-', 'c')
D.a,b,c
AnswerA

Correct string with hyphens.

Why this answer

The `join()` method in Python concatenates the elements of an iterable (here, a list of strings) into a single string, using the string on which it is called as the separator. In this case, `'-'.join(['a', 'b', 'c'])` inserts a hyphen between each element, producing the string `'a-b-c'`. The `print()` function then outputs that string without quotes.

Exam trap

Python Institute often tests whether candidates understand that `join()` returns a single string, not a list or tuple, and that the separator is placed between elements, not appended at the ends.

How to eliminate wrong answers

Option B is wrong because it shows a list `['a', '-', 'b', '-', 'c']`, which would be the result of incorrectly flattening the separator into the list rather than using `join()`. Option C is wrong because it shows a tuple `('a', '-', 'b', '-', 'c')`, which similarly misrepresents the output as a tuple of separate characters. Option D is wrong because `'a,b,c'` uses commas as separators, which would be produced by `','.join(['a', 'b', 'c'])`, not the hyphen separator specified in the question.

132
MCQhard

A cloud infrastructure engineer is developing a Python script to parse large configuration files from a fleet of servers. Each file can be up to 500 MB. The script reads the file line by line using a file object, strips comment lines (those starting with '#'), and accumulates only the configuration directives into a single string for further processing. The current code is: ```python result = '' with open('config.cfg') as f: for line in f: if not line.startswith('#'): result += line.strip() ``` After processing just a few hundred lines of a large file, the script becomes extremely slow and consumes an excessive amount of memory. The engineer identifies that string concatenation using `+=` is inefficient because strings are immutable, causing repeated memory reallocation. Which approach should the engineer implement to resolve the performance issue without changing the final output?

A.Replace `result += line.strip()` with `result = result + line.strip()`.
B.Use `io.StringIO` to write lines and then retrieve content with `.getvalue()`.
C.Use `str.join` called on the file object: `f.join('')`.
D.Use a list to collect stripped lines and then call `''.join(lines)` after the loop.
AnswerD

List append is O(1), and join is efficient, avoiding repeated reallocation.

Why this answer

Option B is correct because collecting lines in a list and joining them at the end avoids repeated string copying, solving the performance issue. Option A is wrong because it still uses concatenation, just with a different operator. Option C is wrong because file objects do not have a `join` method.

Option D is wrong because while `StringIO` works, it is less efficient and not the standard recommended approach; `join` is more direct.

133
MCQeasy

A developer writes a script to read a configuration file that may not exist. The script should handle the error gracefully and continue. Which approach is most Pythonic?

A.Use a try-except block catching FileNotFoundError
B.Use a try-except block catching OSError
C.Use os.path.exists to check, then open if it exists
D.Use an if statement to check file size
AnswerA

EAFP; clean and recommended for this scenario.

Why this answer

Option A is correct because it directly catches the specific `FileNotFoundError` exception, which is a subclass of `OSError` and is raised when a file does not exist. This approach follows the Pythonic principle of EAFP (Easier to Ask for Forgiveness than Permission), allowing the script to attempt the operation and handle the failure gracefully without redundant checks.

Exam trap

Python Institute often tests the distinction between catching a specific exception (`FileNotFoundError`) versus a broader parent exception (`OSError`), and the trap here is that candidates may choose the broader catch thinking it is safer, without realizing it can mask other critical errors.

How to eliminate wrong answers

Option B is wrong because catching `OSError` is too broad; it would also catch other operating system errors (e.g., permission denied, disk full) that may require different handling, masking the specific file-not-found scenario. Option C is wrong because using `os.path.exists` introduces a race condition (TOCTOU — Time of Check to Time of Use) where the file could be deleted or created between the check and the open call, and it violates the Pythonic EAFP idiom by using LBYL (Look Before You Leap). Option D is wrong because checking file size does not determine if a file exists; a file with zero size exists, and a non-existent file has no size to check, making this approach logically incorrect and unreliable.

134
MCQeasy

Refer to the exhibit. Which statement correctly creates an instance of `Dog` and calls the `bark` method?

A.d = Dog(); d.bark()
B.d = Dog("Rex"); d.bark()
C.Dog.bark()
D.d = Dog; d.bark()
AnswerB

This correctly creates a Dog with name "Rex" and calls bark().

Why this answer

The `__init__` method requires a `name` argument. Option B passes "Rex" and then calls `bark()` on the instance.

135
MCQeasy

A subclass overrides a method but wants to call the parent class's version. Which keyword should be used?

A.base
B.super()
C.parent
D.self
AnswerB

super() accesses methods of the parent class following MRO.

Why this answer

In Python, the `super()` function is used to call a method from the parent class. When a subclass overrides a method, `super().method_name()` allows the subclass to invoke the parent class's implementation, enabling cooperative multiple inheritance and proper method resolution order (MRO). This is the correct keyword for accessing the parent class's version of an overridden method.

Exam trap

Python Institute often tests the distinction between `super()` and `self`, where candidates mistakenly think `self` can access the parent's overridden method, but `self` always refers to the current instance and will call the subclass's version if overridden.

How to eliminate wrong answers

Option A is wrong because `base` is not a keyword in Python; it is used in C# for accessing base class members, but Python uses `super()`. Option C is wrong because `parent` is not a Python keyword or built-in function; it has no meaning in Python's object-oriented syntax. Option D is wrong because `self` refers to the current instance of the class, not the parent class; it cannot be used to call the parent class's overridden method directly.

136
MCQmedium

You are developing a package 'analytics' that contains subpackages 'stats' and 'ml'. The __init__.py of 'analytics' imports a function 'normalize' from 'analytics.stats'. When a user runs `import analytics`, they get an ImportError. Which change ensures the package imports correctly?

A.Change the import to: from stats import normalize
B.Add sys.path.append('.') before the import in __init__.py
C.Change the import in analytics/__init__.py to: from .stats import normalize
D.Move the import statement to the stats/__init__.py file
AnswerC

Correct. Relative import with dot refers to the same package.

Why this answer

Option C is correct because it uses an explicit relative import (`from .stats import normalize`), which is the proper way to import from a subpackage within a package. Absolute imports like `from analytics.stats import normalize` can fail if the package's parent directory is not in `sys.path`, which is common when running scripts directly. Relative imports resolve correctly based on the package structure, ensuring the import works regardless of how the package is invoked.

Exam trap

Python Institute often tests the distinction between absolute and relative imports in packages, and the trap here is that candidates mistakenly think absolute imports like `from analytics.stats import normalize` are always safe, not realizing they depend on the package being installed or the parent directory being in `sys.path`.

How to eliminate wrong answers

Option A is wrong because `from stats import normalize` uses an absolute import without the package prefix, which will look for a top-level module named `stats` rather than the subpackage `analytics.stats`, causing a ModuleNotFoundError. Option B is wrong because `sys.path.append('.')` adds the current working directory to the module search path, which is unreliable and does not guarantee that the package's parent directory is in `sys.path`; it also violates best practices by modifying `sys.path` in `__init__.py`. Option D is wrong because moving the import to `stats/__init__.py` would not make `normalize` available at the `analytics` package level when a user runs `import analytics`; the import must be in `analytics/__init__.py` to be part of the package's namespace.

137
Matchingmedium

Match each Python operator to its precedence level (1=highest).

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

Concepts
Matches

1

3

4

7

8

Why these pairings

Operator precedence in Python (simplified).

138
MCQmedium

A team is developing a data processing pipeline where each step is a class that implements a common interface. They have defined an abstract base class DataProcessor with an abstract method process(data). Several concrete subclasses implement process. Now they need to add a new step that logs the data before processing. They want to reuse the existing processing logic without modifying the original classes. Which design pattern should they apply?

A.Factory pattern to instantiate processors dynamically.
B.Decorator pattern by creating a LoggingProcessor subclass that wraps another processor and calls its process method after logging.
C.Singleton pattern to ensure only one logger exists.
D.Observer pattern to notify loggers of data changes.
AnswerB

Decorator pattern adds responsibility dynamically without modifying the original class.

Why this answer

The Decorator pattern allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. By creating a LoggingProcessor that wraps an existing DataProcessor and delegates to its process method after logging, the team reuses the original processing logic without modifying the existing classes, adhering to the Open/Closed Principle.

Exam trap

Python Institute often tests the Decorator pattern in scenarios where the requirement is to add responsibilities to objects dynamically without altering their structure, and the trap is that candidates confuse it with the Factory pattern because both involve creating objects, but the Decorator focuses on extending behavior, not on instantiation logic.

How to eliminate wrong answers

Option A is wrong because the Factory pattern is used to encapsulate object creation logic, not to add new behavior to existing objects; it would not help in adding logging without modifying the original classes. Option C is wrong because the Singleton pattern ensures a single instance of a class (e.g., a logger), but it does not provide a mechanism to wrap or extend the behavior of existing DataProcessor objects. Option D is wrong because the Observer pattern defines a one-to-many dependency for event notification, which is not suitable for wrapping a single processor to add logging before its execution.

139
MCQmedium

A company has a shared internal library stored in a Git repository. Developers need to use this library in multiple projects without copying the code. Which approach is the most Pythonic and maintainable?

A.Add the library's directory to sys.path in each project's main script.
B.Create a symbolic link to the library's directory inside each project.
C.Package the library as a proper Python package and install it via pip in each project's virtual environment.
D.Copy the library source code into each project's directory.
AnswerC

Best practice; ensures version control and isolation.

Why this answer

Option C is correct because packaging the library as a proper Python package and installing it via pip in each project's virtual environment follows the Python packaging standard (PEP 517/518) and the principle of explicit dependency management. This approach ensures versioning, isolation, and easy updates without modifying sys.path or relying on fragile filesystem links, making it the most maintainable and Pythonic solution.

Exam trap

Python Institute often tests the misconception that modifying sys.path or using symbolic links is acceptable for sharing code, when in fact the Pythonic and maintainable solution is to package the library and install it via pip.

How to eliminate wrong answers

Option A is wrong because modifying sys.path at runtime is a fragile workaround that bypasses Python's import system and can cause namespace collisions or import order issues, especially in larger projects. Option B is wrong because symbolic links are platform-dependent, break easily when the repository is cloned or moved, and do not integrate with Python's packaging or dependency resolution tools. Option D is wrong because copying source code defeats the purpose of sharing a library, leads to code duplication, and makes updates impossible without manually synchronizing every project.

140
MCQhard

A developer is building a large string by concatenating many substrings in a loop using '+'. What is the main performance issue?

A.Each concatenation creates a new string object, leading to quadratic time complexity
B.String concatenation is not allowed in loops
C.Strings are immutable, so concatenation is impossible
D.The '+' operator works only for characters, not strings
AnswerA

Correct: repeatedly creating new strings is inefficient.

Why this answer

In Python, strings are immutable, so the '+' operator does not modify an existing string but creates a new string object each time it is used. In a loop, this results in O(n²) time complexity because each concatenation copies the entire accumulated string, making it highly inefficient for large or many substrings.

Exam trap

Python Institute often tests the misconception that string immutability means concatenation is impossible or illegal, when in fact the real issue is the hidden performance cost of repeated object creation in loops.

How to eliminate wrong answers

Option B is wrong because string concatenation using '+' is syntactically allowed inside loops in Python; the issue is performance, not legality. Option C is wrong because while strings are immutable, concatenation is still possible—it creates a new string rather than modifying the original. Option D is wrong because the '+' operator is overloaded for strings and works perfectly for concatenating two or more strings, not just characters.

141
MCQeasy

A developer defines a class with an __init__ method that sets instance attributes. Which of the following is the correct way to call the parent class's __init__ from a child class?

A.super(self, Child).__init__(arg1, arg2)
B.Parent.__init__(self, arg1, arg2)
C.Child.__init__(self, arg1, arg2)
D.super().__init__(arg1, arg2)
AnswerD

super() returns a proxy object that delegates method calls to the parent class, and __init__ is called automatically with self.

Why this answer

In Python, to call the parent class's __init__ method, you should use super().__init__() with the appropriate arguments. This ensures proper initialization in inheritance hierarchies.

142
Matchingmedium

Match each Python module to its purpose.

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

Concepts
Matches

Mathematical functions

Generate pseudo-random numbers

Manipulate dates and times

Work with JSON data

Interact with operating system

Why these pairings

Common Python standard library modules.

143
MCQhard

Consider the code fragment: f = open('data.txt', 'r') data = f.read() process_data(data) f.close() What is the primary risk if an exception occurs during process_data(data)?

A.The file descriptor may be leaked because the close() call is skipped.
B.The exception will be silently suppressed.
C.The file will be automatically closed by Python's garbage collector immediately.
D.The file contents will be corrupted.
AnswerA

Correct: if an exception occurs, close() is not called.

Why this answer

Option A is correct because if `process_data(data)` raises an exception, the `f.close()` statement is never executed, leaving the file descriptor open. This is a resource leak that can exhaust system file handles, especially in long-running applications. Python's `with` statement is the recommended approach to guarantee automatic cleanup even when exceptions occur.

Exam trap

Python Institute often tests the misconception that Python's garbage collector immediately closes files, when in reality it only closes them during an unpredictable collection cycle, making explicit cleanup essential.

How to eliminate wrong answers

Option B is wrong because exceptions are not silently suppressed; they propagate up the call stack unless caught by an explicit `try-except` block. Option C is wrong because Python's garbage collector does not immediately close file descriptors; it may close them at an indeterminate time, and relying on it is poor practice and can lead to resource exhaustion. Option D is wrong because an exception during `process_data(data)` does not corrupt the file contents on disk; the file was opened in read mode, and the data is already read into memory before the exception occurs.

144
Multi-Selectmedium

Which TWO of the following are true about the 'with' statement in Python file I/O?

Select 2 answers
A.It can only be used with file objects
B.It is equivalent to a try/finally block
C.It automatically closes the file after the block
D.It does not require an __exit__ method
E.It requires the object to have an __enter__ method only
AnswersB, C

The 'with' statement ensures cleanup just like try/finally.

Why this answer

Option B is correct because the 'with' statement in Python is designed to simplify exception handling by encapsulating the setup and teardown of a resource in a context manager, which is functionally equivalent to a try/finally block. When you use 'with', the context manager's __exit__ method is guaranteed to be called even if an exception occurs, ensuring that cleanup actions like closing a file are performed, just as a finally clause would.

Exam trap

Python Institute often tests the misconception that the 'with' statement is only for file I/O, but the trap here is that candidates forget the context manager protocol requires both __enter__ and __exit__ methods, not just one, and that it applies to any object implementing that protocol.

145
Multi-Selectmedium

Which three statements about the Method Resolution Order (MRO) in Python are true? (Choose three.)

Select 3 answers
A.The MRO can be viewed using the __mro__ attribute.
B.MRO is determined by the C3 linearization algorithm.
C.The MRO is only used for methods, not attributes.
D.In diamond inheritance, the topmost base class is visited last.
E.The MRO can be changed by modifying the class hierarchy at runtime.
AnswersA, B, D

Each class has a __mro__ attribute showing the order.

Why this answer

Option A is correct because every Python class has an `__mro__` attribute that returns a tuple of classes in the order they are searched for methods and attributes. This attribute is automatically generated by the C3 linearization algorithm and provides a clear, inspectable view of the resolution order.

Exam trap

Python Institute often tests the misconception that the MRO only applies to methods, when in fact it governs all attribute lookups, including data attributes and descriptors.

146
MCQeasy

A package named 'utilities' contains a submodule 'strings'. Which import statement allows the use of the function 'reverse' defined in utilities.strings as reverse() without needing to prefix it?

A.import utilities.strings
B.from utilities import strings
C.from utilities import *
D.from utilities.strings import reverse
AnswerD

Directly imports the function into the current namespace.

Why this answer

Option D is correct because it directly imports the `reverse` function from the `utilities.strings` submodule into the current namespace, allowing it to be called as `reverse()` without any prefix. This is the only option that imports the specific function rather than the module or package.

Exam trap

The trap here is that candidates often confuse importing a module or submodule with importing a specific attribute, leading them to pick options like A or B that still require a prefix, or option C which incorrectly assumes wildcard imports descend into submodules.

How to eliminate wrong answers

Option A is wrong because `import utilities.strings` imports the submodule, requiring the full qualified name `utilities.strings.reverse()` to call the function. Option B is wrong because `from utilities import strings` imports the `strings` submodule into the current namespace, so the function must be called as `strings.reverse()`. Option C is wrong because `from utilities import *` imports all names defined in the `utilities` package's `__init__.py`, not from its submodules; it does not import `reverse` from `utilities.strings` unless explicitly re-exported.

147
MCQmedium

A programmer writes a function to check if a string is a palindrome (ignoring case and non-alphanumeric characters). Which implementation correctly achieves this?

A.def is_pal(s): s = s.lower(); return s == ''.join(reversed(s))
B.def is_pal(s): s = ''.join(c for c in s if c.isalnum()).lower(); return s == s[::-1]
C.def is_pal(s): return s == s[::-1]
D.def is_pal(s): s = s.lower(); return s == s[::-1]
AnswerB

Correctly filters alphanumeric, lowercases, and compares reverse.

Why this answer

Option B is correct because it first filters the string to keep only alphanumeric characters using `c.isalnum()`, converts the result to lowercase with `.lower()`, and then compares the string to its reverse using slicing `s[::-1]`. This correctly handles case insensitivity and ignores non-alphanumeric characters, which is the standard approach for palindrome checking in Python.

Exam trap

Python Institute often tests the requirement to ignore non-alphanumeric characters and case, and the trap here is that candidates may forget to filter the string before reversing, leading them to choose options A or D which only handle case but not punctuation.

How to eliminate wrong answers

Option A is wrong because it only converts the string to lowercase but does not remove non-alphanumeric characters, so strings like 'A man, a plan, a canal: Panama' would fail. Option C is wrong because it performs a direct comparison without any case normalization or character filtering, so it would incorrectly reject palindromes with mixed case or punctuation. Option D is wrong because it converts to lowercase but does not strip non-alphanumeric characters, leading to false negatives for strings containing spaces or punctuation.

148
MCQeasy

A developer wants a class 'Point' to have a readable string representation that returns 'Point(x, y)'. Which special method should be overridden?

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

__repr__ should return a string that, ideally, could be used to recreate the object.

Why this answer

The `__repr__` method is designed to return an unambiguous string representation of an object, often used for debugging and development. Overriding `__repr__` to return `'Point(x, y)'` fulfills the requirement for a readable string representation that matches the specified format. This method is called by the `repr()` built-in function and by the interactive interpreter when evaluating an expression.

Exam trap

Python Institute often tests the distinction between `__repr__` and `__str__`, where candidates mistakenly choose `__str__` because they think 'readable' refers to user-friendly output, but the question's specific format 'Point(x, y)' is the classic `__repr__` pattern for unambiguous object representation.

How to eliminate wrong answers

Option B is wrong because `__format__` is used by the `format()` built-in function and f-strings to produce a formatted string based on a format specification, not to define a general readable representation. Option C is wrong because `__str__` returns an informal, user-friendly string representation (used by `print()` and `str()`), but the question specifically asks for a 'readable string representation' that returns 'Point(x, y)', which is the canonical format for `__repr__`; while `__str__` could be used, the standard practice and the question's phrasing point to `__repr__` as the correct special method for an unambiguous representation. Option D is wrong because `__unicode__` is a Python 2 method for returning a Unicode string; in Python 3, all strings are Unicode, and `__str__` serves that purpose, making `__unicode__` irrelevant in modern Python (and not part of the PCAP exam scope).

149
MCQmedium

Refer to the exhibit. What is the output when this code is executed?

A.AttributeError
B.0
C.None
D.100
AnswerA

Name mangling prevents direct access to __balance.

Why this answer

Option A is correct because the code attempts to access the attribute `balance` on an instance of the `BankAccount` class, but the class defines only `__init__` and `deposit` methods, and no `balance` attribute is ever set. In Python, accessing a non-existent attribute raises an `AttributeError`, not returning a default value or silently failing.

Exam trap

Python Institute often tests the misconception that accessing a missing attribute in Python returns a default value like `None` or `0`, when in fact it raises an `AttributeError` unless the class defines `__getattr__` or `__getattribute__`.

How to eliminate wrong answers

Option B is wrong because it suggests the output is `0`, which would only happen if `balance` were explicitly initialized to `0` in `__init__` (e.g., `self.balance = 0`), but no such assignment exists. Option C is wrong because `None` would be returned only if `balance` were a method that returns nothing, or if the attribute existed and was set to `None`; here the attribute does not exist at all. Option D is wrong because `100` would require `balance` to be set to `100` somewhere, such as via `self.balance = 100` in `__init__` or after a deposit, but the code never creates or assigns a `balance` attribute.

150
MCQmedium

You are working on a Python-based data processing pipeline that runs on a Linux server. The pipeline consists of several custom packages and modules located in /opt/mypipeline. The directory structure includes: /opt/mypipeline/ __init__.py core/ __init__.py processor.py utils/ __init__.py logger.py The main entry point is /opt/mypipeline/run.py, which imports modules from core and utils. The pipeline is executed using the command: python /opt/mypipeline/run.py Recently, the system administrator added a new Python package 'external_lib' to /opt/external_lib, and updated the PYTHONPATH environment variable to include /opt/external_lib. However, after this change, the pipeline fails to start with the following error: ImportError: cannot import name 'process' from 'core.processor' (unknown location) You check the PYTHONPATH and find it contains: /opt/mypipeline:/opt/external_lib The 'core.processor' module defines a function 'process' that is imported in run.py as: from core.processor import process The 'core' package has an __init__.py file. The 'external_lib' package also has a subpackage named 'core' with an __init__.py. What is the most likely cause of the import error?

A.The 'external_lib' package contains a 'core' subpackage that shadows the 'core' package from mypipeline, and Python is resolving to the wrong one.
B.The __init__.py file in /opt/mypipeline/core/ is missing or empty.
C.The import statement in run.py is incorrect; it should use 'from core.processor import process as process' or similar.
D.The PYTHONPATH environment variable is set incorrectly; it should include /opt/mypipeline before /opt/external_lib.
AnswerA

Both packages have a 'core' subpackage. Depending on sys.path order, Python might import the wrong 'core' package, causing the import of 'processor' to fail.

Why this answer

The most likely cause is that the 'external_lib' package contains a 'core' subpackage, which shadows the 'core' package from mypipeline. When Python resolves the import 'from core.processor import process', it searches the directories listed in PYTHONPATH in order. Since PYTHONPATH includes both /opt/mypipeline and /opt/external_lib, and the 'core' subpackage in external_lib is found first (or its presence causes a conflict), Python may resolve to the wrong 'core' package, which does not contain a 'processor' module, leading to the ImportError.

Exam trap

Python Institute often tests the concept of package shadowing where a third-party package with the same name as a local package causes import errors, and candidates mistakenly think the issue is with PYTHONPATH order or missing __init__.py files.

How to eliminate wrong answers

Option B is wrong because the __init__.py files in /opt/mypipeline/core/ are present (as stated in the directory structure), and even if they were missing or empty, that would not cause an 'unknown location' error; it would instead prevent Python from treating the directory as a package, leading to a ModuleNotFoundError. Option C is wrong because the import statement 'from core.processor import process' is syntactically correct and does not require renaming; the error is not due to the import syntax but due to package resolution. Option D is wrong because the PYTHONPATH already lists /opt/mypipeline before /opt/external_lib, so the order is correct; the issue is that the 'core' subpackage in external_lib still interferes because Python may find it via other mechanisms (e.g., if external_lib is installed as a package or if the 'core' directory in external_lib is also a top-level package).

Page 1

Page 2 of 7

Page 3

All pages