Certified Associate Python Programmer PCAP (PCAP) — Questions 226300

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

Page 3

Page 4 of 7

Page 5
226
MCQmedium

A developer is building a logging system that writes logs to a file. The system should handle disk-full situations gracefully without crashing the main application. Which approach is appropriate?

A.Check disk space before each write; if low, skip logging.
B.Wrap the entire application in a try/except that catches all exceptions.
C.Let the OSError propagate to the main program's exception handler.
D.Wrap the log write in a try/except that catches OSError and writes to stderr as fallback.
AnswerD

Catches disk-full errors and logs to stderr, keeping app running.

Why this answer

Option D is correct because it uses a targeted try/except block around only the log write operation, catching OSError (which includes disk-full conditions) and falling back to stderr. This prevents the main application from crashing while still reporting the error, adhering to the principle of handling exceptions at the point where they occur and only when you can meaningfully recover.

Exam trap

Python Institute often tests the distinction between catching overly broad exceptions (Option B) versus catching specific exceptions (Option D), and the trap here is that candidates may think 'catching all exceptions' is a safe catch-all, but it actually hides programming errors and violates Python best practices.

How to eliminate wrong answers

Option A is wrong because checking disk space before each write is unreliable (race conditions, non-atomic check-then-act) and adds unnecessary overhead; it also does not handle other OSError scenarios like permission errors. Option B is wrong because wrapping the entire application in a blanket try/except that catches all exceptions (including KeyboardInterrupt, SystemExit) is an anti-pattern that masks bugs, violates the principle of catching specific exceptions, and can leave the application in an inconsistent state. Option C is wrong because letting OSError propagate to the main program's exception handler typically results in an unhandled exception that terminates the application, which is exactly what the developer wants to avoid.

227
MCQeasy

A junior developer is writing a script that processes user input. The script reads a line of text from the console and needs to remove any leading or trailing whitespace. The developer uses the strip() method but notices that it also removes other characters like newline. However, the requirement is to remove only spaces (not tabs or newlines). Which course of action should the developer take to remove only leading and trailing spaces?

A.Use replace(' ', '') on the string
B.Use lstrip() and rstrip() with no arguments
C.Use split() and join()
D.Use strip(' ') with a space argument
AnswerD

Correct: strip() with specified characters removes only those characters from the ends.

Why this answer

The strip() method without arguments removes all whitespace, including tabs and newlines. To remove only spaces, use strip(' ') which removes only the space character. lstrip() and rstrip() with no arguments also remove all whitespace. replace() removes all spaces everywhere, not just at ends. split() and join() would remove and rejoin with default separator, altering the string.

228
MCQhard

Given the code: s = 'Python'; t = s; s = s + '3.0'. What is the value of t after these lines execute?

A.It raises an error because s was reassigned.
B.''
C.'Python3.0'
D.'Python'
AnswerD

t originally pointed to the same object as s, but when s is reassigned, t still references the original 'Python'.

Why this answer

Option D is correct because strings in Python are immutable. The assignment `t = s` makes `t` reference the same string object as `s`. When `s = s + '3.0'` executes, a new string object `'Python3.0'` is created and bound to `s`, while `t` still references the original string `'Python'`.

Thus, `t` remains `'Python'`.

Exam trap

Python Institute often tests the misconception that variable assignment creates a copy of the value, when in fact it creates a reference; candidates mistakenly think `t` will reflect the new value of `s` after reassignment.

How to eliminate wrong answers

Option A is wrong because reassigning `s` does not raise an error; Python allows variable reassignment freely. Option B is wrong because `t` is never assigned an empty string; it is assigned the original value of `s`, which is `'Python'`. Option C is wrong because `t` does not get updated when `s` is reassigned; `t` still points to the original immutable string `'Python'`, not the new concatenated string `'Python3.0'`.

229
Multi-Selectmedium

Which TWO of the following are valid ways to raise an exception in Python?

Select 2 answers
A.raise
B.raise Exception
C.throw ValueError('error')
D.raise Exception('error')
E.raise ValueError('invalid value')
AnswersD, E

Correct syntax to raise an exception with message.

Why this answer

Option D is correct because `raise Exception('error')` is the standard Python syntax to raise an exception with a custom message. The `raise` keyword is followed by an exception class (or instance), and passing a string argument provides an error message that is stored in the exception's `args` attribute. This is the most common and explicit way to raise an exception in Python.

Exam trap

Python Institute often tests the distinction between `raise` and `throw` to catch candidates who are familiar with other languages, and the fact that `raise` alone is only valid in an `except` block, not as a standalone statement.

230
MCQeasy

A Python script imports the module 'my_module'. The developer wants to ensure that when the script is run directly, it executes a specific function, but when imported as a module, that function is not executed. Which code snippet achieves this?

A.if __name__ == '__main__': run()
B.if __name__ == '__main__': run()
C.if os.environ.get('RUN_MAIN'): run()
D.if sys.argv[0] == 'my_module': run()
AnswerB

This is the standard Python idiom for executable scripts.

Why this answer

Option B is correct because the `if __name__ == '__main__':` guard is the standard Python idiom to check whether a script is being run directly (as the main program) or being imported as a module. When the script is executed directly, Python sets the special variable `__name__` to the string `'__main__'`, so the function `run()` is called. When the script is imported, `__name__` is set to the module's name (e.g., `'my_module'`), so the condition fails and `run()` is not executed.

Exam trap

Python Institute often tests the distinction between `__name__` and `sys.argv` or environment variables, trapping candidates who confuse the script's filename with the module's name or who think an external flag is needed to control execution.

How to eliminate wrong answers

Option A is wrong because it is identical to option B and not a distinct code snippet; in the context of the question, both A and B are the same correct answer, but only one can be selected. Option C is wrong because `os.environ.get('RUN_MAIN')` checks for an environment variable that is not automatically set by Python; this would require manual configuration and does not reflect the standard import-time vs. run-time behavior. Option D is wrong because `sys.argv[0]` contains the script name or path used to invoke the interpreter, not the module name; it would never equal `'my_module'` when the script is imported, and it fails to distinguish between direct execution and import.

231
Multi-Selecteasy

Which TWO of the following are built-in exceptions in Python? (Select exactly 2.)

Select 2 answers
A.InputError
B.ValueError
C.DataError
D.FileNotFoundError
E.CustomError
AnswersB, D

ValueError is a built-in exception raised when a function gets an argument of correct type but inappropriate value.

Why this answer

ValueError is a built-in exception in Python, raised when a built-in operation or function receives an argument with the correct type but an inappropriate value, such as int('abc'). It is part of Python's standard exception hierarchy and does not require any import.

Exam trap

Python Institute often tests candidates by including plausible-sounding exception names like InputError or DataError that mimic real-world patterns but are not part of Python's built-in exception hierarchy, leading candidates to confuse custom or third-party exceptions with standard ones.

232
MCQhard

A developer is implementing a caching system where object instances should be reused if they have the same set of initialization parameters. They want to control object creation so that calling MyClass(param1, param2) returns the same instance if it has been created before, otherwise creates a new one. They are considering overriding __new__ to implement this caching. However, they also need to ensure that __init__ is not called again for cached instances. What is the correct way to achieve this?

A.Override __new__ to return a cached instance, and override __init__ to do nothing if already initialized.
B.Use a class method as an alternative constructor and store instances in a class-level dictionary.
C.Override __call__ on the class metaclass.
D.Override __new__ to return a cached instance if exists, and skip __init__ by checking if the instance is from cache.
AnswerB

This avoids the __new__/__init__ issue entirely by not using the constructor directly; the class method controls caching.

Why this answer

Option B is correct because using a class method as an alternative constructor allows the developer to control instance creation and reuse without interfering with Python's normal object creation protocol. By storing instances in a class-level dictionary keyed by the initialization parameters, the class method can return a cached instance if it exists, or create a new one via the normal constructor (which calls __new__ and __init__). This approach cleanly avoids calling __init__ on cached instances, since the cached object is simply returned directly without invoking the constructor again.

Exam trap

Python Institute often tests the misconception that overriding __new__ alone can prevent __init__ from being called on cached instances, but in reality Python always calls __init__ on the object returned by __new__ unless the returned object is of a different type.

How to eliminate wrong answers

Option A is wrong because overriding __init__ to do nothing if already initialized does not prevent __init__ from being called; Python always calls __init__ on the object returned by __new__, even if that object already exists. Option C is wrong because overriding __call__ on the metaclass changes how the class itself is called (i.e., when you call the class to create an instance), but it does not directly solve the problem of skipping __init__ for cached instances; it would require additional logic to bypass __init__, which is not straightforward. Option D is wrong because even if __new__ returns a cached instance, Python will still call __init__ on that instance unless the object's class is a different type or __init__ is explicitly bypassed via a custom mechanism (e.g., using a flag), which is error-prone and not a standard pattern.

233
MCQhard

What is the output of the Python code after reading the config.txt file?

A.8080 (as string)
B.An exception is raised.
C.8080
D.'8080'
AnswerC

getint returns integer 8080.

Why this answer

The code reads the config.txt file and splits its content by newlines. The first line contains 'port=8080', and after splitting by '=', the second element is '8080'. The int() function converts this string to the integer 8080, which is then printed.

Option C is correct because the output is the integer 8080, not a string or quoted form.

Exam trap

The trap here is that candidates confuse the internal data type (string vs integer) with the printed output, assuming that because the source is a string, the output must also be a string or quoted, when in fact int() converts it to an integer and print() displays it without quotes.

How to eliminate wrong answers

Option A is wrong because the output is an integer, not a string; int() converts the string '8080' to an integer, so the printed value is 8080 without quotes. Option B is wrong because no exception is raised: the file is opened successfully, split operations are valid, and int('8080') is a valid conversion. Option D is wrong because the output is the integer 8080, not the string '8080' with quotes; print() outputs the integer representation without quotes.

234
MCQmedium

A developer needs to count the number of occurrences of the substring 'is' in the string 'This is a test. Is this a test?'. Which code correctly performs the count?

A.'This is a test. Is this a test?'.split().count('is')
B.'This is a test. Is this a test?'.count('is')
C.'This is a test. Is this a test?'.index('is')
D.'This is a test. Is this a test?'.find('is')
AnswerB

Correctly counts overlapping? No, count does not count overlapping, but 'is' appears at positions 5 and 17, not overlapping, so returns 2.

Why this answer

Option B is correct because Python's string method `count(substring)` returns the number of non-overlapping occurrences of the substring in the string. In 'This is a test. Is this a test?', 'is' appears twice (in 'This' and 'is'), and the method counts them correctly, ignoring case sensitivity (the capitalized 'Is' is not counted).

Exam trap

Python Institute often tests the distinction between string methods that return indices (`find`, `index`) versus those that return counts (`count`), and the trap here is that candidates confuse `count()` with `find()` or `index()`, or incorrectly assume `split().count()` works for substring counting.

How to eliminate wrong answers

Option A is wrong because `split()` breaks the string into a list of words (e.g., ['This', 'is', 'a', 'test.', 'Is', 'this', 'a', 'test?']), and then `count('is')` on that list counts only exact list element matches, not substring occurrences — it would return 1 (for the word 'is'), not 2. Option C is wrong because `index('is')` returns the index of the first occurrence of the substring (2) and raises a ValueError if not found, not a count. Option D is wrong because `find('is')` returns the index of the first occurrence (2) or -1 if not found, not a count.

235
MCQhard

Refer to the exhibit. What is the output?

A.'100'
B.100
C.True
D.Error
AnswerB

The integer value 100.

Why this answer

The code `print('100')` outputs the string `100` without quotes. In Python, `print()` displays the value passed to it; when a string literal is passed, it prints the characters of the string, not the surrounding quotes. Therefore, the output is `100` (the integer-like string, but as a string).

Option B is correct because it shows the numeric value without quotes, which is how Python's `print()` renders a string.

Exam trap

The trap here is that candidates confuse the string literal representation (with quotes) with the printed output, mistakenly thinking that `print('100')` will display the quotes as part of the output.

How to eliminate wrong answers

Option A is wrong because it shows the output with single quotes around `100`, but Python's `print()` function does not include quotes in the output; quotes are only used in the source code to denote a string literal. Option C is wrong because `'100'` is a string, not a boolean; printing it does not produce `True` or `False`. Option D is wrong because the code is syntactically valid and runs without error; `print('100')` is a standard Python statement.

236
MCQeasy

If the file 'config.json' exists but contains invalid JSON, what is printed?

A.Unexpected error
B.The program crashes with an unhandled exception.
C.Missing config file
D.Invalid JSON
AnswerD

Correct: JSONDecodeError is caught.

Why this answer

Option D is correct because the code explicitly catches `json.JSONDecodeError` (or `ValueError` in older Python versions) when parsing the file content. If the JSON is invalid, this exception is raised and caught by the `except (json.JSONDecodeError, ValueError)` block, which prints 'Invalid JSON'. The file exists, so the `except FileNotFoundError` block is not triggered.

Exam trap

Python Institute often tests the distinction between file existence errors (`FileNotFoundError`) and content parsing errors (`json.JSONDecodeError`), trapping candidates who assume any file problem results in a generic crash or a missing-file message.

How to eliminate wrong answers

Option A is wrong because 'Unexpected error' is not printed; the code has a specific handler for invalid JSON, not a generic catch-all. Option B is wrong because the program does not crash; the exception is caught, preventing an unhandled crash. Option C is wrong because 'Missing config file' is only printed if `FileNotFoundError` is raised, which requires the file to be absent, but the file exists (albeit with invalid content).

237
Multi-Selectmedium

Which TWO are valid ways to create a multiline string in Python?

Select 2 answers
A.s = ('Line1\n' 'Line2')
B.s = """Line1 Line2"""
C.s = '''Line1 Line2'''
D.s = "Line1\ Line2"
E.s = 'Line1 Line2'
AnswersA, B

Implicit string concatenation with newline escape.

Why this answer

Option A is correct because Python allows implicit string concatenation: adjacent string literals (even across lines within parentheses) are joined into a single string at compile time. The newline escape sequence `\n` in the first literal produces a multiline string without a physical line break in the source code.

Exam trap

Python Institute often tests the distinction between physical line continuation (backslash) and actual multiline string creation (triple quotes or implicit concatenation with `\n`), trapping candidates who think a backslash at line end produces a multiline string.

238
MCQhard

Refer to the exhibit. What is the output?

A.Hi, World!
B.Hello, World!
C.HELLO, WORLD!
D.HI, WORLD!
AnswerD

Correct after both operations.

Why this answer

The correct answer is D because the code uses the `upper()` method on the string `'Hi, World!'`, which converts all lowercase letters to uppercase. The output is `'HI, WORLD!'`. The `upper()` method does not modify the original string but returns a new string with all characters in uppercase.

Exam trap

Python Institute often tests whether candidates notice the exact original string value, as many mistakenly assume the output is 'HELLO, WORLD!' from a common greeting like 'Hello, World!' rather than the actual string 'Hi, World!'.

How to eliminate wrong answers

Option A is wrong because it shows the original string unchanged, but the `upper()` method was called, so the output must be all uppercase. Option B is wrong because it shows 'Hello, World!' which is a different string entirely, not the result of calling `upper()` on `'Hi, World!'`. Option C is wrong because it shows 'HELLO, WORLD!' which would be the result of calling `upper()` on 'Hello, World!', not on 'Hi, World!'.

239
Multi-Selecteasy

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

Select 2 answers
A.Define a method named `property` inside the class.
B.Override `__getattribute__` and check the attribute name.
C.Override `__getattr__` to simulate a property.
D.Use `property(getter, setter)` as a class variable.
E.Use the @property decorator on a method.
AnswersD, E

Correct: property() creates a property descriptor.

Why this answer

Option D is correct because `property(getter, setter)` is a built-in function that returns a property object, which can be assigned as a class variable to define a managed attribute. Option E is correct because the `@property` decorator is the standard, concise way to define a read-only property by decorating a method that acts as the getter.

Exam trap

Python Institute often tests the distinction between defining a property via the `property()` function or `@property` decorator versus overriding dunder methods like `__getattr__` or `__getattribute__`, which are attribute interception hooks, not property definitions.

240
MCQhard

A developer creates a package named 'analytics' with the following structure: analytics/ __init__.py stats.py models/ __init__.py regression.py The developer wants the statement 'from analytics import *' to import only the functions 'mean' and 'std' from stats.py. What should be added to analytics/__init__.py?

A.Nothing; by default, all names are exported.
B.from analytics.stats import *
C.__all__ = ['stats.mean', 'stats.std']
D.__all__ = ['mean', 'std']
AnswerD

This defines the public API of the package.

Why this answer

Option D is correct because in Python, the `__all__` variable in a package's `__init__.py` explicitly controls which names are exported when `from package import *` is used. By setting `__all__ = ['mean', 'std']`, the developer ensures that only the functions `mean` and `std` from `stats.py` are imported into the namespace, as Python will look up these names in the package's scope after executing the `__init__.py` file. This overrides the default behavior where all public names (those not starting with an underscore) would be exported.

Exam trap

Python Institute often tests the misconception that `__all__` can contain dotted paths like `'stats.mean'` to control imports from submodules, when in reality `__all__` only accepts simple attribute names that exist in the package's own namespace.

How to eliminate wrong answers

Option A is wrong because by default, `from analytics import *` does NOT export all names; it exports only names that do not start with an underscore, but more importantly, it does not automatically import submodules unless they are explicitly imported in `__init__.py` or listed in `__all__`. Option B is wrong because `from analytics.stats import *` would import all public names from `stats.py` into the `analytics` package's namespace, but it does not restrict the import to only `mean` and `std`; it would import everything from `stats.py` that is not underscore-prefixed. Option C is wrong because `__all__` must contain simple names (like `'mean'` and `'std'`), not dotted paths like `'stats.mean'`; Python will look for these names directly in the package's namespace, not traverse submodules.

241
MCQhard

Which of the following expressions returns True if the string s contains only hexadecimal digits (0-9, a-f, A-F)?

A.s.isdigit() or s.isalpha()
B.s.isnumeric()
C.s.isalnum() and s.islower()
D.all(c in '0123456789abcdefABCDEF' for c in s)
AnswerD

Correct: Checks each character against the set of valid hex digits.

Why this answer

The most reliable way is to check each character against a set of valid hex digits. Option C does exactly that. Other options are too broad or incorrect.

242
MCQhard

An application needs to dynamically load a module whose name is provided at runtime (stored in a variable 'mod_name'). Which function from the importlib module should be used?

A.importlib.reload(mod_name)
B.importlib.load_module(mod_name)
C.importlib.import(mod_name)
D.importlib.import_module(mod_name)
AnswerD

This function is designed for programmatic module loading.

Why this answer

Option D is correct because `importlib.import_module(mod_name)` is the standard Python function designed to dynamically import a module given its name as a string at runtime. It returns the module object, allowing the application to load and use modules whose names are not known until execution.

Exam trap

Python Institute often tests the distinction between `importlib.import_module()` and the non-existent `importlib.import()` or the deprecated `imp.load_module()`, exploiting candidates' tendency to guess based on similar-sounding names rather than precise API knowledge.

How to eliminate wrong answers

Option A is wrong because `importlib.reload()` is used to re-import an already loaded module, not to load a module by name for the first time. Option B is wrong because `importlib.load_module()` does not exist in the standard `importlib` module; it was part of the deprecated `imp` module. Option C is wrong because `importlib.import()` is not a valid function; the correct function name is `import_module`, not `import`.

243
MCQmedium

A function is supposed to return True if a string contains only digits, and False otherwise. Which implementation uses a Python string method correctly?

A.return s.isdecimal()
B.return s.isnumeric()
C.return s.isalnum() and not s.isalpha()
D.return s.isdigit()
AnswerD

Correctly returns True for strings containing only digits.

Why this answer

isdigit() checks if all characters in the string are digits (0-9 and other Unicode digits), which is the standard method for this purpose.

244
Multi-Selecthard

Which THREE statements about the Python method resolution order (MRO) are true? (Select exactly 3.)

Select 3 answers
A.The MRO is determined at runtime when a method is called.
B.The MRO of a class can be viewed using the __mro__ attribute.
C.C3 linearization is the algorithm used for MRO in Python 3.
D.Python uses a depth-first left-to-right algorithm for MRO.
E.super() uses the MRO to determine which method to call.
AnswersB, C, E

Correct: __mro__ is a tuple of classes in MRO order.

Why this answer

Option B is correct because the `__mro__` attribute on a class returns a tuple of classes in the exact order that Python uses to resolve methods and attributes. This attribute is computed at class definition time using the C3 linearization algorithm, and it provides a direct, read-only view of the resolution order for that class.

Exam trap

Python Institute often tests the misconception that MRO is determined dynamically at runtime (option A) or that Python still uses a simple depth-first left-to-right algorithm (option D), when in fact Python 3 exclusively uses the C3 linearization algorithm computed at class definition time.

245
Matchingmedium

Match each Python built-in function to its description.

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

Concepts
Matches

Returns the length of an object

Generates a sequence of numbers

Returns a sorted list from an iterable

Returns index and value pairs

Aggregates elements from multiple iterables

Why these pairings

These are common built-in functions in Python.

246
MCQhard

Given the string s = 'Hello World!', which expression returns a list of characters?

A.s.split('')
B.list(s)
C.s.split()
D.s.split(' ')
AnswerB

Converts string to list of characters.

Why this answer

Option B is correct because the `list()` constructor, when passed a string, iterates over each character in the string and returns a list where each element is a single character. For `s = 'Hello World!'`, `list(s)` produces `['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']`, which is exactly a list of characters.

Exam trap

Python Institute often tests the distinction between `list(s)` and `s.split()` to catch candidates who confuse splitting a string into words with converting it into a list of characters, especially when the delimiter is omitted or set to an empty string.

How to eliminate wrong answers

Option A is wrong because `s.split('')` raises a `ValueError: empty separator` in Python; the `split()` method requires a non-empty separator string. Option C is wrong because `s.split()` with no arguments splits on any whitespace and discards empty strings, returning `['Hello', 'World!']`, which is a list of words, not characters. Option D is wrong because `s.split(' ')` splits on a single space character, returning `['Hello', 'World!']`, again a list of words, not individual characters.

247
Multi-Selecteasy

Which TWO statements about static methods (@staticmethod) are correct?

Select 2 answers
A.They do not receive an implicit first argument.
B.They can access instance attributes via self.
C.They can access class variables only via cls.
D.They are defined using the @staticmethod decorator.
E.They can only be defined inside a metaclass.
AnswersA, D

Correct: no self or cls.

Why this answer

Option A is correct because static methods in Python do not receive an implicit first argument like `self` (for instance methods) or `cls` (for class methods). They behave like plain functions but belong to a class's namespace, and are called without any automatic parameter injection.

Exam trap

Python Institute often tests the distinction between `@staticmethod` and `@classmethod`, and the trap here is that candidates confuse static methods with class methods, assuming static methods can access class variables via `cls` or instance attributes via `self`.

248
Multi-Selecthard

Given s = 'a1b2c3', which TWO of the following expressions return the string '123'?

Select 2 answers
A.s[0:5:2]
B.s[1::2]
C.s[1:6:2]
D.s[0::2]
E.s[2:5:1]
AnswersB, C

Step 2 from index 1: '1', '2', '3'.

Why this answer

Option B is correct because slicing with `s[1::2]` starts at index 1 (the character '1'), goes to the end of the string, and takes every second character, resulting in '1', '2', '3' concatenated as '123'. Option C is also correct because `s[1:6:2]` starts at index 1, stops before index 6 (the string length is 6, so index 6 is just past the last character), and steps by 2, yielding the same sequence of characters.

Exam trap

Python Institute often tests the misconception that slicing with a step of 2 always starts from index 0, causing candidates to overlook the correct starting index needed to isolate digits from a mixed string.

249
MCQhard

A company has a large Python application that uses multiple packages from different directories. The application's main entry point is at /opt/app/main.py. There is a package 'common' located at /opt/app/common/ and another package 'services' at /opt/app/services/. Both packages have __init__.py files. Additionally, there is a third-party package 'utils' installed in the system site-packages. Recently, a developer added a new module 'helpers.py' to the 'common' package. When trying to import 'common.helpers' from a script inside 'services', an ImportError is raised: 'No module named common.helpers'. However, importing 'common' itself works. The sys.path includes /opt/app/ and the site-packages. What is the most likely cause of the import failure?

A.The 'helpers.py' file was added after the Python interpreter started, and sys.modules caching prevents new imports.
B.There is another 'common' package elsewhere in sys.path that shadows the intended one, and the shadowed package does not have a 'helpers' submodule.
C.The PYTHONPATH environment variable is not set, so the /opt/app/ directory is not searched.
D.The 'common' package itself is already imported and cached, so adding a new module does not become visible.
AnswerB

If another directory with a 'common' package appears earlier in sys.path, Python imports that one instead.

Why this answer

Option B is correct because the most likely cause is that a different 'common' package (without a 'helpers' submodule) appears earlier in sys.path and shadows the intended /opt/app/common/ package. Since sys.path includes /opt/app/ and site-packages, if a 'common' package exists in site-packages or another directory listed before /opt/app/, Python will import that shadowed package instead, and it lacks the newly added 'helpers' module. This explains why importing 'common' succeeds (the shadowed package exists) but 'common.helpers' fails.

Exam trap

Python Institute often tests the subtlety that a package can be shadowed by another package with the same name earlier in sys.path, leading to successful import of the parent but failure for submodules that exist only in the intended package.

How to eliminate wrong answers

Option A is wrong because Python does not automatically cache modules based on file modification time; sys.modules caching only prevents re-importing a module that was already imported, but it does not prevent importing a newly added module if the package was not previously imported. Option C is wrong because the sys.path already includes /opt/app/ (as stated), so PYTHONPATH is not required for that directory to be searched. Option D is wrong because even if 'common' was previously imported, Python's import system checks for new submodules by searching the package's __path__ on disk, not just sys.modules; the issue is not caching but a shadowing conflict.

250
Multi-Selecthard

Which THREE of the following are true about Python's object-oriented programming features?

Select 3 answers
A.Python supports method overloading based on argument types
B.Python supports multiple inheritance
C.All methods are virtual in the sense that they can be overridden
D.Python enforces access modifiers like private and protected
E.Operator overloading can be implemented by defining special methods like __add__
AnswersB, C, E

Yes, a class can inherit from multiple base classes.

Why this answer

Option B is correct because Python's class hierarchy supports multiple inheritance, allowing a class to inherit from more than one parent class. This is a core feature of Python's object-oriented programming model, implemented via the C3 linearization algorithm (Method Resolution Order, or MRO) to resolve method and attribute lookups unambiguously.

Exam trap

Python Institute often tests the misconception that Python supports method overloading like Java or C++, leading candidates to incorrectly select Option A, when in fact Python uses dynamic typing and late binding to handle different argument patterns through default or variable arguments.

251
MCQmedium

A developer creates a package 'mypackage' with the following structure: mypackage/ __init__.py module1.py module2.py The __init__.py contains: from mypackage.module1 import func1 from mypackage.module2 import func2 __all__ = ['func1', 'func2'] In a separate script, the developer writes: from mypackage import * print(func1()) This works as expected. However, when the developer runs the same script from a different directory (not the one containing mypackage), the import works but the script prints an error that func1 is not defined. What could be the problem?

A.The current working directory is not in sys.path, so the package cannot be found.
B.The __all__ variable hides func1 because it does not include it, but it does.
C.The mypackage directory lacks proper __init__.py (maybe it is not present or invalid), causing it to be treated as a namespace package, and the __init__.py is never executed.
D.The imports in __init__.py are relative imports and fail when run from a different directory.
AnswerC

If __init__.py is missing or not executed, the functions are not imported into the package namespace.

Why this answer

Option D is correct. If 'mypackage' is a directory without an __init__.py (maybe it was accidentally deleted or the directory is not a proper package), Python may treat it as a namespace package. In that case, the __init__.py is not executed, so func1 and func2 are not imported.

However, the import itself might succeed if the directory is found via namespace packaging. Option A is wrong because sys.path does not include the current directory by default in newer Python versions; but the import would fail entirely if the package were not found. Option B is wrong because __all__ is defined, so it does not hide func1.

Option C is wrong because relative imports are not used here; the imports in __init__.py are absolute.

252
MCQeasy

Your team is developing a large application with many packages. To avoid name conflicts, you decide to use namespace packages. You have two directories: /team/common/ and /team/analytics/. Both contain an __init__.py file. You want to create a namespace package 'team' that combines these two directories. You create a directory /team/ with no __init__.py. You then set PYTHONPATH to /team/common/ and /team/analytics/ (actually, you set it to the parent directories). But when you try to `from team.common import something`, you get ModuleNotFoundError. What is the most likely reason?

A.The presence of __init__.py in 'common' and 'analytics' prevents them from being part of a namespace package.
B.The PYTHONPATH should point to the parent directory of 'team', not to the subdirectories directly.
C.The namespace package requires an __init__.py in the parent directory as well.
D.The sys.path must also include the 'team' directory itself.
AnswerB

Python expects the namespace package 'team' to be a directory directly under a path in sys.path.

Why this answer

Option B is correct because for namespace packages to work, PYTHONPATH must point to the parent directory of the 'team' namespace package, not to the subdirectories 'common' and 'analytics' directly. When PYTHONPATH includes '/team/common/' and '/team/analytics/', Python treats each as a separate top-level package, so 'from team.common import something' fails because 'team' is not found as a package. The correct setup is to set PYTHONPATH to the directory containing 'team' (e.g., '/team/'), allowing Python to discover 'team' as a namespace package and then locate 'common' and 'analytics' as sub-packages.

Exam trap

The trap here is that candidates often assume __init__.py is always required for packages, leading them to think its presence in subdirectories is the problem (Option A), or they mistakenly believe the namespace package itself needs an __init__.py (Option C), when in fact the key requirement is that the parent directory must be __init__.py-free and PYTHONPATH must point to the parent of the namespace package, not to the subdirectories.

How to eliminate wrong answers

Option A is wrong because the presence of __init__.py in 'common' and 'analytics' does not prevent them from being part of a namespace package; in fact, they are regular packages that can be merged under a namespace package as long as the parent 'team' directory lacks __init__.py. Option C is wrong because namespace packages explicitly require the absence of __init__.py in the parent directory ('team') to allow multiple directories to contribute to the same namespace; adding an __init__.py would turn 'team' into a regular package, defeating the purpose. Option D is wrong because sys.path does not need to include the 'team' directory itself; Python automatically traverses directories listed in sys.path to find packages, and including the parent directory is sufficient for namespace resolution.

253
Multi-Selecthard

Which THREE of the following are true about Python's exception hierarchy?

Select 3 answers
A.KeyboardInterrupt inherits from BaseException.
B.SystemExit inherits from BaseException.
C.IOError is a separate class from OSError.
D.ZeroDivisionError inherits from ArithmeticError.
E.GeneratorExit inherits from Exception.
AnswersA, B, D

Correct: KeyboardInterrupt is under BaseException.

Why this answer

Option A is correct because `KeyboardInterrupt` inherits directly from `BaseException`, not from `Exception`. This design ensures that `KeyboardInterrupt` (raised by Ctrl+C) is not caught by a generic `except Exception:` clause, allowing the program to be interrupted even when broad exception handling is in place.

Exam trap

Python Institute often tests the misconception that `GeneratorExit` inherits from `Exception` (it actually inherits from `BaseException`), and that `IOError` is a separate class from `OSError` (it is an alias in Python 3).

254
MCQeasy

A developer wants to distribute a package that contains both Python code and data files (e.g., images, configs). Which file is used to specify dependencies and metadata for the package?

A.setup.py
B.MANIFEST.in
C.__init__.py
D.requirements.txt
AnswerA

The standard for packaging.

Why this answer

Option B is correct because setup.py is the traditional script for packaging, defining dependencies, metadata, and data files. Option A is wrong because __init__.py initializes packages but does not define dependencies. Option C is wrong because requirements.txt lists dependencies for pip but is not part of the built package metadata.

Option D is wrong because MANIFEST.in specifies additional files to include in the source distribution, but not dependencies.

255
Multi-Selectmedium

Which TWO of the following can be used to remove leading whitespace (spaces, tabs, newlines) from a string? (Choose exactly 2 correct answers.)

Select 2 answers
A.rstrip()
B.lstrip()
C.trim()
D.clean()
E.strip()
AnswersB, E

lstrip() specifically removes leading whitespace.

Why this answer

Option A (lstrip()) removes leading whitespace. Option D (strip()) removes both leading and trailing whitespace, which includes leading whitespace. Option B (rstrip()) removes trailing, not leading.

Option C (trim()) is not a Python string method. Option E (clean()) does not exist.

256
Multi-Selecteasy

Which of the following statements about class inheritance in Python are true? (Choose two.)

Select 2 answers
A.A class can inherit from only one base class.
B.Abstract base classes can be defined using the ABC module.
C.A child class can override any method from its parent class, but only if the method is declared as virtual.
D.The super() function is used to call a method from a sibling class.
E.Python supports multiple inheritance.
AnswersB, E

The abc module provides the ABC class and abstractmethod decorator.

Why this answer

Option B is correct because Python's `abc` module (Abstract Base Classes) allows you to define abstract base classes by inheriting from `ABC` and using the `@abstractmethod` decorator. This enforces that subclasses must implement the abstract methods, providing a formal interface contract.

Exam trap

Python Institute often tests the misconception that `super()` only calls a parent method, but in multiple inheritance it actually calls the next class in the MRO, which could be a sibling or a cousin, not necessarily a direct parent.

257
MCQeasy

A developer is implementing a simple counter class. The class should start at 0 and increment by 1 each time the 'increment' method is called. Which implementation is correct?

A.class Counter:\n def __init__(self):\n self.count = 0\n def increment(self):\n count = self.count + 1
B.class Counter:\n def __init__(self):\n self.count = 0\n def increment(self):\n self.count += 1
C.class Counter:\n def __init__(self):\n count = 0\n def increment(self):\n count += 1
D.class Counter:\n def __init__(self):\n self.count = 0\n def increment():\n self.count += 1
AnswerB

Correctly defines instance variable and increments.

Why this answer

Option B is correct because it properly initializes an instance variable `self.count` to 0 in the `__init__` method and then uses `self.count += 1` in the `increment` method to modify the instance variable in place. The `+=` operator is a shorthand for `self.count = self.count + 1`, which correctly updates the counter each time `increment` is called.

Exam trap

Python Institute often tests the distinction between local variables and instance variables in methods, trapping candidates who forget to prefix `self` when accessing or modifying object attributes.

How to eliminate wrong answers

Option A is wrong because `count = self.count + 1` creates a local variable `count` inside the `increment` method instead of updating the instance variable `self.count`, so the counter never changes. Option C is wrong because `count = 0` in `__init__` creates a local variable instead of an instance variable, and `count += 1` in `increment` tries to modify a local variable that hasn't been initialized in that scope, causing a `NameError`. Option D is wrong because the `increment` method is missing the required `self` parameter, so calling `increment()` will raise a `TypeError` about missing positional arguments.

258
MCQmedium

When importing a module, Python searches for it in a specific order. Which of the following lists the correct order of directories searched?

A.PYTHONPATH then sys.path
B.[current directory] then PYTHONPATH then site-packages
C.sys.path + [current directory]
D.[current directory] + sys.path
AnswerD

Correct. Python first adds the script's directory to sys.path, then the rest of sys.path.

Why this answer

When Python imports a module, it first searches the directory containing the input script (or the current working directory if no script is specified), then iterates through the directories listed in the PYTHONPATH environment variable, and finally checks the installation-dependent default paths (such as site-packages). This order is reflected in the composition of sys.path, which is built from the script directory, PYTHONPATH entries, and default site-packages. Option D correctly states that the current directory is searched before the rest of sys.path, which includes PYTHONPATH and site-packages.

Exam trap

Python Institute often tests the misconception that PYTHONPATH is searched before the current directory, or that sys.path is a static list rather than a dynamically built sequence starting with the script's directory.

How to eliminate wrong answers

Option A is wrong because PYTHONPATH is not searched before sys.path; rather, PYTHONPATH entries are inserted into sys.path after the current directory, so the search order is current directory, then PYTHONPATH, then site-packages. Option B is wrong because it omits the fact that the current directory is searched first, but it incorrectly lists 'site-packages' as a separate step after PYTHONPATH; in reality, site-packages is part of sys.path and is searched after PYTHONPATH, not as a distinct third step. Option C is wrong because it suggests that sys.path is searched before the current directory, which reverses the actual order; the current directory is always prepended to sys.path, making it the first location searched.

259
Multi-Selecthard

Which TWO of the following statements about Python's `sys.path` are true?

Select 3 answers
A.The current working directory is always the first element in `sys.path`.
B.Module search stops at the first matching directory in `sys.path`.
C.`sys.path` is initialized from the PYTHONPATH environment variable.
D.`sys.path` is a tuple of strings.
E.The directory containing the script being run is added to the beginning of `sys.path` at startup.
AnswersB, C, E

Python searches sys.path in order and stops when it finds the module.

Why this answer

Option B is correct because Python's import mechanism iterates through the directories listed in `sys.path` in order and stops searching as soon as it finds the first module or package matching the import name. This means the first match in the list is used, and no further directories are checked.

Exam trap

Python Institute often tests the distinction between the current working directory and the script's directory, as well as the mutable nature of `sys.path` (list vs. tuple), to catch candidates who confuse initialization details with runtime behavior.

260
MCQmedium

A developer wants to remove leading and trailing whitespace from a string. Which method should be used?

A.s.lstrip()
B.s.trim()
C.s.rstrip()
D.s.strip()
AnswerD

Removes whitespace from both ends.

Why this answer

Option D is correct because the `strip()` method in Python removes both leading and trailing whitespace (including spaces, tabs, and newlines) from a string. This is the standard method for trimming whitespace from both ends, as specified in Python's string documentation.

Exam trap

Python Institute often tests the distinction between `strip()`, `lstrip()`, and `rstrip()`, and the trap here is that candidates may confuse `strip()` with the non-existent `trim()` method from other languages, or think `lstrip()` or `rstrip()` alone suffice for full trimming.

How to eliminate wrong answers

Option A is wrong because `lstrip()` only removes leading whitespace from the left side, not trailing whitespace. Option B is wrong because `trim()` is not a valid Python string method; it exists in other languages like Java or JavaScript but not in Python. Option C is wrong because `rstrip()` only removes trailing whitespace from the right side, not leading whitespace.

261
MCQeasy

A programmer wants to ensure that a class attribute is the same for all instances and can be accessed via the class name. Which type of variable should be defined?

A.Global variable
B.Instance variable
C.Local variable inside a method
D.Class variable
AnswerD

Class variables are shared and accessed via class name.

Why this answer

Option D is correct because a class variable in Python is defined directly within the class body (outside any method) and is shared across all instances. It can be accessed via the class name (e.g., `ClassName.var`) or through any instance, ensuring the same value for all objects.

Exam trap

Python Institute often tests the misconception that a class variable can be safely modified via an instance, but the trap is that doing so creates an instance variable that shadows the class variable, leaving the original class variable unchanged for other instances.

How to eliminate wrong answers

Option A is wrong because a global variable is defined at the module level, not inside a class, and is not inherently tied to the class or its instances; it can be modified from anywhere, breaking encapsulation. Option B is wrong because an instance variable is unique to each object (defined with `self` in `__init__`), so it is not the same for all instances. Option C is wrong because a local variable inside a method exists only within that method's scope and cannot be accessed via the class name or by other methods.

262
MCQhard

A team is developing a banking system in Python. They have a base class Account with attributes account_number and balance, and a method __init__(self, account_number, balance) that initializes these attributes. They then create a subclass SavingsAccount that adds an attribute interest_rate. In SavingsAccount's __init__, they assign self.interest_rate = rate but do not call super().__init__. When they instantiate SavingsAccount('12345', 1000, 0.02) and attempt to print(balance), an AttributeError occurs: 'SavingsAccount' object has no attribute 'balance'. What is the most appropriate fix to ensure that the SavingsAccount includes balance and account_number without code duplication?

A.Remove the __init__ method from SavingsAccount entirely and rely on the default __init__ from Account.
B.Manually assign self.account_number and self.balance in SavingsAccount.__init__ before assigning interest_rate.
C.Call super().__init__(account_number, balance) as the first line in SavingsAccount.__init__, then assign self.interest_rate = rate.
D.Define balance as a class attribute in Account with a default value and remove it from __init__.
AnswerC

This correctly delegates to the base class and adds the new attribute.

Why this answer

The fix is to call super().__init__ to reuse the base class initialization and then add the subclass-specific attribute. Option A duplicates code, option C changes the architecture unnecessarily, and option D removes necessary initialization.

263
MCQhard

A Python package 'mypackage' contains the following hierarchy: mypackage/ __init__.py subpackage1/ __init__.py module_a.py subpackage2/ __init__.py module_b.py From a script outside the package, a programmer writes: import mypackage.subpackage1.module_a Which statement is true about the import?

A.Only mypackage/__init__.py is executed.
B.No __init__.py files are executed because the import uses a dotted path.
C.After the import, 'mypackage' is not available as a name in the namespace.
D.Both mypackage/__init__.py and mypackage/subpackage1/__init__.py are executed.
AnswerD

Python executes __init__.py for each package in the dotted path when importing a submodule.

Why this answer

When Python encounters an import statement with a dotted path like `import mypackage.subpackage1.module_a`, it executes the `__init__.py` files for each package in the path in order: first `mypackage/__init__.py`, then `mypackage/subpackage1/__init__.py`. This is because Python must initialize each package before it can access its subpackages or modules. Option D correctly states that both `__init__.py` files are executed.

Exam trap

Python Institute often tests the misconception that dotted imports skip `__init__.py` execution or that only the final module is loaded, when in fact Python executes every `__init__.py` along the dotted path to ensure proper package initialization.

How to eliminate wrong answers

Option A is wrong because Python does not stop at the top-level package; it must also execute `subpackage1/__init__.py` to initialize that subpackage before importing `module_a`. Option B is wrong because `__init__.py` files are always executed when their corresponding package is imported, regardless of whether the import uses a dotted path or a direct package name. Option C is wrong because after `import mypackage.subpackage1.module_a`, the name `mypackage` is bound in the namespace as a reference to the top-level package object, allowing access via `mypackage.subpackage1.module_a`.

264
Multi-Selectmedium

Which THREE of the following are true about the __pycache__ directory?

Select 3 answers
A.It is only created when the script is compiled with -O.
B.It is automatically created when a module is imported.
C.It improves startup time for subsequent runs.
D.It stores compiled bytecode files (.pyc).
E.It should be added to version control.
AnswersB, C, D

Python creates __pycache__ on first import.

Why this answer

Option B is correct because Python automatically creates the __pycache__ directory when a module is imported for the first time. This directory stores compiled bytecode files (.pyc) that allow Python to skip recompilation on subsequent imports, thereby improving startup time for later runs.

Exam trap

Python Institute often tests the misconception that __pycache__ is only created with -O or that it should be version-controlled, when in fact it is automatically generated on import and is meant to be excluded from version control.

265
MCQmedium

Which of the following is the correct way to format a string to include a variable value with two decimal places in Python?

A.f"{value:.2f}"
B.f"{value:.2}"
C.f"{value%:.2f}"
D.f"{value:2f}"
AnswerA

Correct: :.2f formats with two decimal places.

Why this answer

In an f-string, the format specifier :.2f is used to format a float with two decimal places. Option B is the correct syntax.

266
MCQeasy

Which of the following is a valid way to import a module named 'math' and assign it an alias 'm'?

A.alias math as m
B.from math import * as m
C.import m from math
D.import math as m
AnswerD

Correct. This imports the module and assigns it the alias m.

Why this answer

Option D is correct because Python's `import` statement allows you to import a module and assign it an alias using the `as` keyword, as in `import math as m`. This creates a reference to the `math` module under the name `m`, so you can call functions like `m.sqrt(16)` without polluting the namespace with the original module name.

Exam trap

Python Institute often tests the misconception that `alias` is a Python keyword or that `from ... import *` can be combined with `as`, leading candidates to pick options A or B instead of the correct `import ... as ...` syntax.

How to eliminate wrong answers

Option A is wrong because `alias` is not a valid Python keyword; the correct syntax uses `import ... as ...`, not `alias`. Option B is wrong because `from math import *` imports all names from the module into the current namespace, and the `as m` clause is not allowed with the `from ... import *` form; aliasing is only supported with a single imported name or module. Option C is wrong because the syntax `import m from math` is invalid; Python requires the module name to come immediately after `import`, and the alias (if any) must follow the `as` keyword.

267
MCQeasy

A developer needs to check if a filename starts with the prefix 'report_'. Which string method should be used?

A.prefix()
B.startswith()
C.starts()
D.beginwith()
AnswerB

Correct because str.startswith(prefix) checks the start of the string.

Why this answer

The `startswith()` method is the correct string method in Python to check if a string begins with a specified prefix. It returns `True` if the string starts with the given substring, otherwise `False`, making it the exact tool for checking if a filename starts with 'report_'.

Exam trap

Python Institute often tests the exact naming of Python string methods, and the trap here is that candidates may confuse `startswith()` with similar-sounding but non-existent methods like `starts()` or `beginwith()`, or incorrectly assume a method like `prefix()` exists based on other programming languages.

How to eliminate wrong answers

Option A is wrong because `prefix()` is not a valid Python string method; no such method exists in the standard library. Option C is wrong because `starts()` is not a valid Python string method; the correct method name is `startswith()`. Option D is wrong because `beginwith()` is not a valid Python string method; Python uses `startswith()` for this purpose, not `beginwith()`.

268
Multi-Selecteasy

Which TWO of the following string methods return a boolean value?

Select 2 answers
A.startswith()
B.capitalize()
C.format()
D.swapcase()
E.isalpha()
AnswersA, E

Returns True or False.

Why this answer

The `startswith()` method returns `True` if the string starts with the specified prefix, otherwise `False`. Similarly, `isalpha()` returns `True` if all characters in the string are alphabetic and there is at least one character, otherwise `False`. Both methods explicitly return a boolean value (`True` or `False`), making them correct choices.

Exam trap

The trap here is that candidates often confuse methods that return a new string (like `capitalize()`, `swapcase()`) with methods that return a boolean, because both are called on string objects and appear similar in syntax.

269
MCQeasy

A developer is writing a function that validates a user input string to ensure it contains only ASCII digits (0-9) for a numeric ID field. Which method should be used to check the string?

A.isdecimal()
B.isnumeric()
C.isdigit()
D.isalpha()
AnswerC

isdigit() returns True for all digit characters, including ASCII digits 0-9, and is the appropriate check.

Why this answer

Option C is correct because isdigit() returns True for strings that consist only of decimal digits (0-9) in the Unicode sense, but for ASCII digits it works correctly. Option A (isnumeric()) also returns True for numeric characters like '½', so it is too broad. Option B (isdecimal()) is limited to decimal numbers and can fail on some digits.

Option D (isalpha()) checks for alphabetic characters only.

270
MCQeasy

A developer wants to import a specific function 'calculate' from a module named 'formulas' without importing the entire module. Which import statement should be used?

A.import formulas
B.import calculate from formulas
C.from formulas import calculate
D.import formulas as f
AnswerC

This imports only the specified function.

Why this answer

Option C is correct because the `from module import name` syntax in Python allows you to import a specific function (or other attribute) from a module directly into the current namespace, without importing the entire module. This avoids unnecessary memory usage and keeps the namespace clean by only bringing in the needed `calculate` function.

Exam trap

Python Institute often tests the distinction between importing a module versus importing a specific attribute, and the trap here is that candidates may confuse the invalid `import calculate from formulas` syntax (Option B) with the correct `from formulas import calculate` syntax, or think that `import formulas` (Option A) is sufficient to use the function directly.

How to eliminate wrong answers

Option A is wrong because `import formulas` imports the entire module, requiring the function to be accessed as `formulas.calculate`, not directly as `calculate`. Option B is wrong because `import calculate from formulas` is invalid Python syntax; the correct order is `from formulas import calculate`. Option D is wrong because `import formulas as f` imports the entire module under an alias, still requiring `f.calculate` to call the function, and does not import the function directly.

271
MCQhard

An abstract base class (ABC) defines an abstract method `process()`. Several subclasses implement it. A function accepts any subclass and calls `process()`. This demonstrates which OOP concept?

A.Inheritance.
B.Encapsulation.
C.Method overloading.
D.Polymorphism.
AnswerD

The same interface (process) works differently for different subclasses.

Why this answer

Option D is correct because polymorphism allows objects of different subclasses to be treated uniformly through their common interface. When a function accepts any subclass of the ABC and calls `process()`, the correct implementation is resolved at runtime via dynamic dispatch, which is the essence of polymorphism in Python.

Exam trap

Python Institute often tests the distinction between inheritance and polymorphism by presenting a scenario where multiple subclasses override a method, leading candidates to mistakenly select 'inheritance' because they see the class hierarchy, but the key behavior is the polymorphic call, not the inheritance itself.

How to eliminate wrong answers

Option A is wrong because inheritance alone only establishes a parent-child relationship and code reuse; it does not guarantee that the same method call behaves differently across subclasses. Option B is wrong because encapsulation is about bundling data and methods together and restricting direct access to internal state, which is not demonstrated by calling a method on different subclass objects. Option C is wrong because method overloading refers to multiple methods with the same name but different parameters within the same class, which Python does not support natively; the scenario here uses a single method signature overridden in subclasses, not overloading.

272
MCQhard

When should you raise a specific exception class rather than a generic Exception?

A.When different error conditions require different handling.
B.Always raise Exception for simplicity.
C.Specific exceptions cannot be created; only built-in ones can be used.
D.Only when performance is a concern.
AnswerA

Correct: specific exceptions enable targeted handling.

Why this answer

Raising a specific exception class (e.g., ValueError, KeyError, or a custom subclass) allows the caller to catch and handle each error condition differently using separate except blocks. Using a generic Exception forces all errors into a single handler, which can mask distinct failure modes and make debugging harder. This aligns with Python's EAFP (Easier to Ask for Forgiveness than Permission) idiom, where precise exception types enable fine-grained error recovery.

Exam trap

Python Institute often tests the misconception that generic Exception is simpler or sufficient, but the trap is that it forces all errors into one catch-all, which hides the need for distinct handling logic and violates Pythonic best practices for exception granularity.

How to eliminate wrong answers

Option B is wrong because always raising generic Exception violates the principle of exception specificity, making it impossible for callers to distinguish between error types without inspecting the message string, which is fragile and discouraged. Option C is wrong because Python allows creation of custom exception classes by subclassing Exception (or any other built-in exception), enabling domain-specific error handling. Option D is wrong because performance is rarely a concern when choosing exception types; the decision should be based on semantic clarity and handling requirements, not optimization.

273
MCQmedium

An application uses a class to represent a configuration object that reads settings from a file. The class has a class attribute config_cache that holds a dictionary of loaded configurations to avoid repeated file reads. However, the developer notices that when they modify the dictionary for one instance, it affects all instances. They want to ensure that each instance has its own copy of the configuration data upon initialization. Which change should they make?

A.Move the dictionary initialization into the __init__ method so each instance creates its own dictionary.
B.Use a @staticmethod to return a new dictionary each time.
C.Keep the class attribute but use a deep copy in __init__ before modifying.
D.Define the dictionary inside a class method.
AnswerA

Initializing in __init__ creates a new dictionary per instance, avoiding sharing.

Why this answer

Option A is correct because moving the dictionary initialization into the __init__ method ensures that each instance gets its own separate dictionary object. Class attributes are shared across all instances, so modifying the dictionary via one instance changes it for all. By assigning `self.config_cache = {}` inside __init__, each instance creates a new, independent dictionary upon instantiation, solving the shared-state problem.

Exam trap

Python Institute often tests the distinction between mutable and immutable class attributes, trapping candidates who think a deep copy in __init__ will fix the sharing issue, when in fact the shared reference to the class attribute itself must be replaced with an instance attribute.

How to eliminate wrong answers

Option B is wrong because a @staticmethod that returns a new dictionary would still need to be called and assigned to an instance attribute; if the result is stored in a class attribute, the sharing issue persists. Option C is wrong because using a deep copy in __init__ before modifying does not prevent the initial shared reference; the class attribute itself remains a single dictionary that all instances point to, so any modification to the original (or a copy made later) still affects the shared object. Option D is wrong because defining the dictionary inside a class method does not change its scope; if the method assigns to a class attribute, it remains shared, and if it returns a new dict, the instance must still store it properly to avoid sharing.

274
MCQeasy

A developer wants to ensure that a class attribute is shared among all instances but cannot be modified from outside the class. Which approach is most appropriate?

A.Use a property decorator on a class method
B.Define a public class attribute and document it as read-only
C.Define an instance attribute inside __init__
D.Define a private class attribute (e.g., __shared) and provide a class method to access it
AnswerD

Name mangling discourages direct access; getter method controls read-only access.

Why this answer

Option D is correct because defining a private class attribute with name mangling (e.g., `__shared`) prevents direct external modification, and providing a class method (using `@classmethod`) allows read-only access to the attribute. This ensures the attribute is shared among all instances (since it belongs to the class, not instances) while enforcing encapsulation.

Exam trap

Python Institute often tests the distinction between class-level and instance-level attributes, and the trap here is that candidates confuse the `@property` decorator (which works on instance methods) with class-level read-only access, or assume documentation alone provides protection.

How to eliminate wrong answers

Option A is wrong because a property decorator is designed for instance attributes, not class attributes; applying it to a class method would not create a shared, read-only class-level attribute. Option B is wrong because documenting a public class attribute as read-only does not enforce immutability — external code can still modify it directly, violating the requirement. Option C is wrong because an instance attribute defined inside `__init__` is unique to each instance, not shared among all instances.

275
MCQeasy

Given the exhibit, why does `dir()` show no names from `mypackage` after executing `from mypackage import *`?

A.The package does not have an `__init__.py` file.
B.The `__init__.py` file must be empty for `from package import *` to work.
C.`__all__` causes submodules to be ignored during `import *`.
D.The `__all__` variable is defined as an empty list, so `from mypackage import *` imports nothing.
AnswerD

`__all__` controls what is imported; an empty list means nothing.

Why this answer

Option D is correct because when a package defines `__all__` as an empty list in its `__init__.py`, the `from mypackage import *` statement imports nothing. The `__all__` variable explicitly controls which names are exported by `import *`, and an empty list means no names are imported. This is a deliberate design to prevent accidental namespace pollution.

Exam trap

The trap here is that candidates often assume `from package import *` always imports all submodules, but Cisco tests the nuance that `__all__` can override this behavior, and an empty `__all__` results in no imports, which is a common point of confusion.

How to eliminate wrong answers

Option A is wrong because a package without an `__init__.py` file is a namespace package (Python 3.3+), and `from package import *` would still attempt to import submodules, though it may raise an ImportWarning or import nothing depending on the Python version; the absence of `__init__.py` does not inherently cause `dir()` to show no names. Option B is wrong because an empty `__init__.py` file is perfectly valid and does not prevent `from package import *` from working; in fact, an empty `__init__.py` is common and allows the package to be recognized as a regular package. Option C is wrong because `__all__` does not cause submodules to be ignored; rather, it explicitly lists which names (including submodules) should be imported when `import *` is used; if `__all__` is defined, only those names are imported, and submodules not listed are ignored.

276
MCQeasy

A script is located in the parent directory of a package named 'mypackage'. Which import statement correctly imports the 'foo' module from the 'mypackage' package?

A.from mypackage import foo
B.import mypackage.foo
C.from .mypackage import foo
D.import foo from mypackage
AnswerA

Correct. This imports the foo module directly into the current namespace.

Why this answer

Option A is correct because when the script is in the parent directory of 'mypackage', Python's import system can locate the package via the current working directory or sys.path. The statement 'from mypackage import foo' directly imports the module 'foo' from the package 'mypackage' without requiring relative import syntax, as the package is a top-level package relative to the script's location.

Exam trap

Python Institute often tests the distinction between absolute and relative imports, and the trap here is that candidates mistakenly use a relative import (option C) thinking the dot is required when the script is 'outside' the package, but relative imports only work from within a package, not from a standalone script in a parent directory.

How to eliminate wrong answers

Option B is wrong because 'import mypackage.foo' imports the module as 'mypackage.foo', requiring you to reference it as 'mypackage.foo' in code, not as 'foo' directly; the question asks to import the 'foo' module, not to access it via a qualified name. Option C is wrong because 'from .mypackage import foo' uses a relative import (the dot), which is only valid inside a package (e.g., within a submodule of a package), not from a script in the parent directory; this would raise an ImportError. Option D is wrong because 'import foo from mypackage' is invalid Python syntax; the correct syntax is 'from mypackage import foo'.

277
MCQeasy

A user runs script.py and gets the above error. Which of the following is the most likely cause?

A.The function myfunction does not exist in mypackage.
B.The script.py is inside the mypackage directory, causing a conflict.
C.The package mypackage is not installed or not in the Python path.
D.There is a syntax error in script.py.
AnswerC

The error clearly states the module is not found.

Why this answer

The error message indicates that Python cannot find the module `mypackage`. This typically happens when the package is not installed (e.g., via pip) or the directory containing it is not in `sys.path`. Option C correctly identifies this as the most likely cause, as Python raises an `ImportError` when it cannot locate a module or package during import.

Exam trap

Python Institute often tests the distinction between `ImportError` (module not found) and `AttributeError` (module found but attribute missing), so candidates mistakenly choose Option A when they see an import-related error, confusing a missing module with a missing function within an existing module.

How to eliminate wrong answers

Option A is wrong because if `myfunction` did not exist in `mypackage`, the error would be an `AttributeError` (e.g., 'module 'mypackage' has no attribute 'myfunction''), not an `ImportError` about the package itself. Option B is wrong because placing `script.py` inside the `mypackage` directory would not cause an `ImportError`; it would actually make the import succeed (assuming `__init__.py` exists), though it could lead to circular imports or naming conflicts, but not the error shown. Option D is wrong because a syntax error in `script.py` would produce a `SyntaxError` at compile time, not an `ImportError` at runtime; the error message explicitly mentions 'ImportError', which is unrelated to syntax issues.

278
Multi-Selecthard

Which THREE of the following are true about the `with` statement for file handling?

Select 3 answers
A.It can only be used with files.
B.It can only handle one file at a time.
C.It uses the __enter__ and __exit__ methods of the file object.
D.It ensures the file is closed even if an exception occurs inside the block.
E.It automatically closes the file when the block exits.
AnswersC, D, E

These methods implement the context manager.

Why this answer

Option C is correct because the `with` statement relies on the context management protocol, which requires the object to implement the `__enter__` and `__exit__` methods. When a file object is used with `with`, its `__enter__` method returns the file object itself, and its `__exit__` method is called upon block exit to handle cleanup, such as closing the file.

Exam trap

Python Institute often tests the misconception that `with` is only for files, but the trap here is that candidates may also incorrectly think it can only handle one file at a time, while Python actually supports multiple context managers in a single `with` statement.

279
MCQeasy

During code review, a team member wrote: 'class Dog(Animal): pass'. The Animal class has an __init__ method that requires a 'name' parameter. When instantiating Dog, what should be done to properly initialize the inherited attributes?

A.Define a new __init__ in Dog that does not call super
B.Dog will automatically inherit the __init__ method
C.Use a decorator to initialize
D.Define __init__ in Dog that calls super().__init__(name)
AnswerD

Proper way to extend parent initialization.

Why this answer

Option D is correct because in Python, when a subclass like Dog inherits from a superclass like Animal, the __init__ method is not automatically called unless explicitly invoked. Since Animal's __init__ requires a 'name' parameter, Dog must define its own __init__ and call super().__init__(name) to ensure the inherited attributes are properly initialized. This follows Python's method resolution order (MRO) and is the standard pattern for cooperative multiple inheritance.

Exam trap

Python Institute often tests the misconception that inheritance automatically runs the parent's __init__ when a subclass is instantiated, leading candidates to incorrectly select Option B without realizing that Python requires explicit super() calls for proper initialization.

How to eliminate wrong answers

Option A is wrong because defining a new __init__ in Dog that does not call super() will override the parent's __init__, leaving the inherited 'name' attribute uninitialized and potentially causing AttributeError when accessing it. Option B is wrong because while Dog does inherit the __init__ method from Animal, it is not automatically called when instantiating Dog; Python only calls __init__ if it is defined in the class or inherited, but the inherited method still requires explicit invocation via super() to run properly in the subclass context. Option C is wrong because Python does not have a built-in decorator for initializing inherited attributes; decorators like @dataclass or @property serve different purposes and do not replace the need for explicit super().__init__() calls.

280
MCQmedium

A file is opened with open('test.txt', 'r'). The file object's tell() method returns 0. After reading 10 characters, what does tell() return?

A.File size
B.0
C.-1
D.10
AnswerD

Correctly reflects the new position.

Why this answer

Option D is correct because the `tell()` method returns the current position of the file pointer in bytes from the beginning of the file. After reading 10 characters (each being 1 byte in a typical text file), the pointer advances by 10 bytes, so `tell()` returns 10.

Exam trap

Python Institute often tests the misconception that `tell()` returns the number of characters read or the file size, when in fact it returns the byte offset from the start of the file.

How to eliminate wrong answers

Option A is wrong because `tell()` does not return the file size; it returns the current offset, not the total length. Option B is wrong because the file pointer moves after reading, so it cannot remain at 0. Option C is wrong because `tell()` never returns -1; it always returns a non-negative integer representing the byte offset.

281
Multi-Selectmedium

Which TWO statements about namespace packages are true?

Select 2 answers
A.They are automatically created when a directory containing .py files is added to sys.path.
B.They are supported in Python 3.3 and later.
C.They allow a single package to be distributed across multiple directories.
D.They can only contain __init__.py files.
E.They require an __init__.py file.
AnswersB, C

Correct. PEP 420 introduced namespace packages in Python 3.3.

Why this answer

Option B is correct because namespace packages were introduced in Python 3.3 via PEP 420. They allow a package to be split across multiple directories on sys.path without requiring an __init__.py file, enabling logical grouping of subpackages from different locations.

Exam trap

Python Institute often tests the misconception that all packages require an __init__.py file, but namespace packages are a deliberate exception introduced in Python 3.3, and candidates may incorrectly assume that any directory with .py files automatically becomes a namespace package.

282
MCQeasy

Refer to the exhibit. Which import statement in app.py will successfully import and use the greet function from helpers.py?

A.import utils.helpers; then greet()
B.from utils.helpers import greet
C.from .utils.helpers import greet
D.from my_package.utils.helpers import greet
AnswerC

Correct relative import: the dot refers to the current package, then into utils.helpers.

Why this answer

Option C is correct because in a package structure, a relative import (using a leading dot) is required to import from a sibling module within the same package. The dot (.) refers to the current package, so `from .utils.helpers import greet` correctly imports the `greet` function from `helpers.py` located in the `utils` subpackage relative to `app.py`.

Exam trap

Python Institute often tests the distinction between absolute and relative imports, and the trap here is that candidates mistakenly use an absolute import (like `from utils.helpers import greet`) without realizing that `app.py` is inside a package, requiring a relative import with a leading dot.

How to eliminate wrong answers

Option A is wrong because `import utils.helpers` would require the module to be accessed as `utils.helpers.greet()`, not `greet()`, and the import statement itself is syntactically valid but the usage is incorrect. Option B is wrong because `from utils.helpers import greet` uses an absolute import without a leading dot, which would only work if `utils` is a top-level package or module in the Python path, not a subpackage of the current package. Option D is wrong because `from my_package.utils.helpers import greet` assumes the top-level package is named `my_package`, which is not indicated in the exhibit; the actual top-level package name is unknown or different, making this import incorrect.

283
MCQmedium

A Python script placed in /opt/myapp/script.py fails with ImportError when run from a cron job with the command: python /opt/myapp/script.py. The script works when run manually from the /opt/myapp/ directory. The script contains the line: from . import config. The config module is located in /opt/myapp/lib/config.py with an __init__.py in /opt/myapp/lib/. What is the most likely cause of the failure?

A.The __init__.py file in the lib directory is empty and should contain imports.
B.The lib directory is not in sys.path when the script is run from cron.
C.Relative imports are not allowed in a script that is executed directly because its __name__ is not set to a package name.
D.The cron job uses a different Python interpreter that does not have the required standard library.
AnswerC

When a script is run directly, it is treated as __main__, not as part of a package, so relative imports fail.

Why this answer

Option C is correct because when a Python script is executed directly (e.g., `python /opt/myapp/script.py`), its `__name__` is set to `'__main__'`, not to a package name. Relative imports (like `from . import config`) require the importing module to be part of a package with a proper `__name__` reflecting the package hierarchy. Since the script is run as the top-level entry point, the relative import fails with an `ImportError`.

This explains why the script works when run manually from `/opt/myapp/` (if the working directory is set appropriately, but the relative import still fails unless the script is run as a module with `-m`), but fails from cron where the working directory is typically the user's home directory.

Exam trap

Python Institute often tests the distinction between running a script directly (`python script.py`) versus running it as a module (`python -m package.script`), and the trap here is that candidates mistakenly blame `sys.path` or `__init__.py` contents instead of recognizing that relative imports are fundamentally incompatible with direct script execution.

How to eliminate wrong answers

Option A is wrong because an empty `__init__.py` is sufficient to mark a directory as a Python package; it does not need to contain imports. The error is not caused by the contents of `__init__.py`. Option B is wrong because the `lib` directory is not directly in `sys.path`; however, the relative import `from . import config` does not rely on `sys.path` — it relies on the package structure and the `__name__` of the script.

The script's failure is not due to missing `sys.path` entries, but due to the prohibition of relative imports in a directly executed script. Option D is wrong because the cron job uses the same Python interpreter as the manual run (both invoke `python`), and the error is an `ImportError` specific to relative imports, not a missing standard library module.

284
MCQhard

A team maintains a library 'utils' with multiple modules. They want to expose a clean public API so that users can do `from utils import helper`. However, they also have internal modules that should not be accessible directly. Which approach best achieves this?

A.Use a single file named 'utils.py' and split functions into classes with private methods.
B.In utils/__init__.py, set __all__ = ['helper'] and rename internal modules with a leading underscore (e.g., _internal).
C.Remove all __init__.py files and rely on the module search path.
D.Name internal modules starting with 'import' to prevent from import *.
AnswerB

This is the standard Python idiom for controlled public API.

Why this answer

Option B is correct because using `__all__` in `__init__.py` explicitly controls what is exported when a user writes `from utils import *`, and renaming internal modules with a leading underscore (e.g., `_internal`) is a Python convention that signals those modules are private and not part of the public API. This combination allows `from utils import helper` to work while preventing direct access to internal modules, as Python's import system respects the underscore convention and `__all__` restricts wildcard imports.

Exam trap

Python Institute often tests the misconception that `__all__` completely blocks access to all non-listed modules, when in reality it only affects `from package import *` and does not prevent direct imports like `from package._internal import something`.

How to eliminate wrong answers

Option A is wrong because splitting functions into classes with private methods in a single file does not prevent users from importing internal modules directly; it only hides functions within a class, and Python's private methods (single/double underscore) are still accessible via name mangling. Option C is wrong because removing all `__init__.py` files would break the package structure entirely, preventing `from utils import helper` from working as a package import and potentially causing import errors or namespace collisions. Option D is wrong because naming internal modules starting with 'import' is syntactically invalid in Python (it would be a reserved keyword) and does not prevent access; Python has no mechanism to block imports based on module name prefixes.

285
MCQmedium

A team is implementing a shape hierarchy with a base class `Shape` that should have an `area()` method. They want to ensure that every subclass must provide its own implementation of `area()`. Which approach should they use?

A.Define `area()` in `Shape` and have it raise `NotImplementedError`.
B.Use a class method that must be overridden.
C.Define `area()` as a property that raises an error.
D.Use `@abstractmethod` from the `abc` module to declare `area()` as abstract.
AnswerD

This enforces that subclasses must implement `area()` and prevents instantiation of `Shape` directly.

Why this answer

Option D is correct because the `abc` module provides the `ABCMeta` metaclass and the `@abstractmethod` decorator, which together enforce that any concrete subclass must override the abstract method. If a subclass fails to implement `area()`, Python raises a `TypeError` at instantiation time, ensuring the design contract is upheld. This is the standard Pythonic way to define abstract base classes and enforce method implementation in subclasses.

Exam trap

Python Institute often tests the distinction between raising `NotImplementedError` (a runtime-only check) and using `@abstractmethod` (which prevents instantiation of incomplete subclasses), leading candidates to mistakenly choose Option A because they think 'raising an error' is sufficient for enforcement.

How to eliminate wrong answers

Option A is wrong because raising `NotImplementedError` at runtime does not enforce compile-time or instantiation-time checks; a subclass can forget to override `area()` and the error will only appear when the method is called, not when the object is created. Option B is wrong because a class method (`@classmethod`) is not designed for abstract method enforcement; it can be overridden but there is no built-in mechanism to require overriding, and the `@abstractmethod` decorator is the correct tool for that purpose. Option C is wrong because defining `area()` as a property that raises an error does not prevent instantiation of a subclass that fails to override the property; the error only occurs when the property is accessed, and properties are not intended for abstract method enforcement.

286
MCQmedium

Consider a class `D` that inherits from multiple base classes `B` and `C`. The developer wants to call a method from a specific parent class while ensuring correct method resolution order (MRO). Which is the safest way?

A.`self.method()`
B.`ParentClass.method(self)`
C.`super().method()`
D.`BaseClass.method(self)`
AnswerC

`super()` follows the MRO, calling the method from the next class in line.

Why this answer

In Python, `super().method()` is the safest way to call a method from a parent class in a multiple inheritance scenario because it respects the Method Resolution Order (MRO) defined by the C3 linearization algorithm. This ensures that the method is resolved from the next class in the MRO, avoiding hard-coded references that could break if the inheritance hierarchy changes. It also correctly handles cooperative multiple inheritance, where each class in the MRO can collaborate via `super()` calls.

Exam trap

Python Institute often tests the misconception that `super()` only calls the immediate parent class, when in fact it follows the full MRO, and candidates mistakenly choose a hard-coded parent call (like Option B or D) thinking it is more explicit and safer.

How to eliminate wrong answers

Option A is wrong because `self.method()` will invoke the method on the instance using the MRO, starting from the class of `self`, which may not call the intended parent class method if the method is overridden in a subclass. Option B is wrong because `ParentClass.method(self)` is a hard-coded reference that bypasses the MRO entirely, leading to potential issues in diamond inheritance or if the class hierarchy is modified. Option D is wrong because `BaseClass.method(self)` is essentially the same as Option B — it directly calls a specific base class method, ignoring the MRO and breaking cooperative multiple inheritance patterns.

287
MCQmedium

You are a developer for an e-commerce platform. The system receives product descriptions from suppliers in various formats. One supplier sends descriptions with inconsistent capitalization, extra whitespace, and occasional leading/trailing punctuation. Your task is to write a function that normalizes these descriptions: convert to lowercase, remove leading/trailing whitespace and punctuation (.,!?;:), and replace multiple spaces with a single space. The function should return the cleaned string. Which implementation correctly performs all these steps?

A.def normalize(s): import re; s = s.strip(); s = s.strip('.,!?;:'); s = s.lower(); s = re.sub(r'\s+', ' ', s); return s
B.def normalize(s): return ' '.join(s.lower().split())
C.def normalize(s): return s.lower().strip('.,!?;: ')
D.def normalize(s): return s.strip().lower()
AnswerA

Correctly strips whitespace, then punctuation, lowercases, and collapses spaces.

Why this answer

Option A is correct because it performs all required steps in the correct order: it first strips leading/trailing whitespace with `strip()`, then removes leading/trailing punctuation using `strip('.,!?;:')`, converts to lowercase with `lower()`, and finally replaces multiple spaces with a single space using `re.sub(r'\s+', ' ', s)`. This ensures that punctuation is removed only from the edges after whitespace is handled, and internal whitespace is normalized last.

Exam trap

Python Institute often tests the order of operations in string normalization, and the trap here is that candidates may think `strip()` with a punctuation argument also handles whitespace or that `split()` and `join()` alone are sufficient to remove punctuation, leading them to choose options that miss one or more required steps.

How to eliminate wrong answers

Option B is wrong because it uses `split()` which splits on any whitespace and removes it entirely, but it does not remove leading/trailing punctuation (e.g., '!Hello' becomes '!hello' after `lower()` and split/join, leaving the exclamation mark). Option C is wrong because `strip('.,!?;: ')` removes only leading/trailing characters from that set, but it does not replace multiple internal spaces with a single space (e.g., 'Hello World' stays with multiple spaces). Option D is wrong because it only strips whitespace and lowercases, ignoring the removal of leading/trailing punctuation and the normalization of multiple internal spaces.

288
MCQmedium

A programmer writes a class with a static method using @staticmethod. What is the primary purpose of using a static method instead of a class method or instance method?

A.To access class variables without creating an instance
B.To define a method that does not depend on class or instance state and behaves like a regular function but is namespaced inside the class
C.To allow the method to be overridden in subclasses
D.To enforce that the method cannot be called from an instance
AnswerB

Static methods are utility functions that belong to the class logically.

Why this answer

Option B is correct because a static method in Python, decorated with @staticmethod, does not receive an implicit first argument (neither self nor cls). This means it cannot access or modify class or instance state; it behaves exactly like a regular function but is organized within the class's namespace for logical grouping. The primary purpose is to encapsulate utility functions that are related to the class but do not depend on its data.

Exam trap

Python Institute often tests the distinction between static and class methods by making candidates think that @staticmethod is used to access class variables, when in fact that is the role of @classmethod, and the trap is that both decorators avoid the need for an instance, but only @classmethod receives the class reference.

How to eliminate wrong answers

Option A is wrong because accessing class variables without an instance is the purpose of a class method (decorated with @classmethod), which receives the class as the first argument (cls) and can read or write class-level attributes; a static method has no access to cls and cannot directly access class variables unless they are passed explicitly. Option C is wrong because static methods are not overridden in subclasses in the same way as instance or class methods; they are resolved at compile time (early binding) and do not participate in the normal method resolution order (MRO) for inheritance, so overriding them has no effect when called on the subclass. Option D is wrong because static methods can be called from an instance just fine; Python allows calling any method from an instance, and @staticmethod does not restrict this — the decorator only removes the implicit self parameter, not the ability to invoke it on an object.

289
MCQhard

Given package structure: pack/__init__.py, pack/subpack/__init__.py, pack/subpack/mod.py. Inside pack/__init__.py, which import statement correctly imports mod.py using a relative import?

A.from . import subpack.mod
B.from subpack import mod
C.from ..subpack import mod
D.from .subpack import mod
AnswerD

Correct. The dot indicates relative import from the current package.

Why this answer

Option D is correct because `from .subpack import mod` uses a leading dot to indicate a relative import from the current package (`pack`), then navigates into `subpack` and imports `mod`. This is the proper syntax for importing a module from a subpackage within the same parent package.

Exam trap

Python Institute often tests the distinction between absolute and relative imports, and the trap here is that candidates mistakenly use an absolute import (Option B) or incorrect dot syntax (Option A or C) because they confuse the number of dots or the placement of the module name in the import statement.

How to eliminate wrong answers

Option A is wrong because `from . import subpack.mod` is invalid syntax; relative imports require the dot to be followed directly by a package or module name, not a dotted path after the import keyword. Option B is wrong because `from subpack import mod` is an absolute import, which would look for a top-level package named `subpack`, not the one inside `pack`. Option C is wrong because `from ..subpack import mod` uses two dots, which would go up one level from `pack` to its parent, not down into `subpack`.

290
MCQeasy

A programmer has a string 'apple,banana,orange' and wants to get a list ['apple', 'banana', 'orange']. Which method should be used?

A.s.splitlines()
B.s.partition(',')
C.s.join(',')
D.s.split(',')
AnswerD

split(',') returns a list of substrings separated by commas.

Why this answer

Option B is correct because str.split(',') splits the string on the comma. Option A is wrong because str.partition() returns a tuple of three parts. Option C is wrong because str.splitlines() splits on line breaks.

Option D is wrong because str.join() is the inverse operation.

291
MCQeasy

A developer needs to add a custom directory '/home/user/mylibs' to Python's module search path so that modules in that directory can be imported. Which code snippet accomplishes this correctly?

A.import sys; sys.path.append('/home/user/mylibs')
B.import sys; sys.path.push('/home/user/mylibs')
C.import sys; sys.path.add('/home/user/mylibs')
D.import path; path.add('/home/user/mylibs')
AnswerA

Correctly adds the directory to the module search path.

Why this answer

Option A is correct because Python's module search path is stored in the list `sys.path`, and the standard way to add a custom directory at runtime is to use the `list.append()` method. This inserts the directory at the end of the search path, allowing modules in that directory to be imported after the standard library and site-packages directories.

Exam trap

The trap here is that candidates may confuse `sys.path` with a stack or set and choose a method like `push()` or `add()` that does not exist for Python lists, or they may incorrectly import a non-existent `path` module instead of `sys`.

How to eliminate wrong answers

Option B is wrong because `sys.path` is a list, and Python lists do not have a `push()` method (that is a method of stacks in other languages, not Python). Option C is wrong because `sys.path` is a list, and lists do not have an `add()` method (that method belongs to sets, not lists). Option D is wrong because there is no standard `path` module in Python that provides an `add()` function for modifying the module search path; the correct module is `sys` and the attribute is `sys.path`.

292
MCQmedium

A developer runs pip install package==1.0 and gets the above error. What is the most likely solution?

A.Run pip update to upgrade pip.
B.Install from a different repository.
C.Use pip install package==2.0 instead.
D.Check if the package name is correct.
AnswerC

Version 2.0 is available and satisfies the requirement.

Why this answer

Option C is correct because the error indicates that version 1.0 of the package does not exist in the repository. By specifying a higher version like 2.0 that does exist, pip can successfully download and install the package. This is a common scenario when a package has never released version 1.0 or has skipped it.

Exam trap

Python Institute often tests the distinction between a missing package name and a missing version number, tricking candidates into checking the name or repository when the error specifically says the version is unavailable.

How to eliminate wrong answers

Option A is wrong because 'pip update' is not a valid pip command; the correct command is 'pip install --upgrade pip', and upgrading pip would not resolve a missing version error. Option B is wrong because the error is about a specific version not being found, not about repository accessibility or authentication; changing the repository would not help if the package itself does not have that version. Option D is wrong because the error message explicitly states the package name was found but version 1.0 is not available, so the name is correct.

293
MCQmedium

A programmer has a string s = 'Python programming is fun'. They want to extract the word 'programming'. Which slicing expression achieves this?

A.s[6:18]
B.s[7:18]
C.s[7:19]
D.s[6:19]
AnswerB

Correct: Extracts indices 7 to 17, which is 'programming'.

Why this answer

The word 'programming' starts at index 7 and ends at index 17 (inclusive). Slicing s[7:18] extracts indices 7 through 17.

294
MCQmedium

A Python package 'analytics' contains a subpackage 'models' with module 'regression.py'. Inside 'regression.py', there is a function 'linear_fit' that depends on 'numpy'. The developer wants to ensure that 'numpy' is imported only once and available throughout the package. Where should the import 'import numpy as np' be placed?

A.In the '__init__.py' of the 'models' subpackage.
B.In each module that uses numpy, add 'import numpy as np'.
C.In the '__init__.py' of the 'analytics' top-level package.
D.In a separate file 'common_imports.py' and import that file everywhere.
AnswerC

Makes numpy accessible as analytics.np and imported once.

Why this answer

Option C is correct because placing 'import numpy as np' in the '__init__.py' of the 'analytics' top-level package ensures that numpy is imported once when the package is first loaded, making it available to all subpackages and modules within the package. This leverages Python's module caching mechanism, where the import is executed only once and the module object is stored in sys.modules, preventing redundant imports and ensuring consistent access across the package.

Exam trap

Python Institute often tests the misconception that imports should be placed in the subpackage '__init__.py' or in each module individually, but the key is that the top-level '__init__.py' is executed once when the package is first imported, making it the correct location for package-wide shared imports.

How to eliminate wrong answers

Option A is wrong because placing the import in the '__init__.py' of the 'models' subpackage would only make numpy available within that subpackage, not throughout the entire 'analytics' package, and it would be imported each time the subpackage is loaded. Option B is wrong because importing numpy in each module that uses it would cause multiple imports, which, while technically allowed due to caching, violates the requirement to import it only once and does not ensure availability throughout the package without explicit imports. Option D is wrong because using a separate 'common_imports.py' file and importing it everywhere still requires explicit imports in each module, and it does not guarantee that numpy is imported only once at the package level; it also adds unnecessary indirection without leveraging Python's package initialization mechanism.

295
Drag & Dropmedium

Drag and drop the steps to perform unit testing with the unittest framework 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

Unit testing with unittest requires importing, creating a TestCase subclass, writing test methods, and calling unittest.main().

296
MCQmedium

A logging module receives a message that may contain sensitive data. To comply with data privacy, all digits in the message should be replaced with 'X' before logging. Which approach correctly achieves this?

A.message.replace('0-9', 'X')
B.re.sub(r'[0-9]', 'X', message)
C.message.translate(str.maketrans('0123456789', 'XXXXXXXXXX'))
D.''.join(['X' if c.isdigit() else c for c in message])
AnswerB

Uses regex to replace any digit character with 'X'.

Why this answer

Option B is correct because `re.sub(r'[0-9]', 'X', message)` uses a regular expression character class `[0-9]` to match any single digit (0-9) and replaces each occurrence with 'X'. This is the standard Python approach for pattern-based string replacement, and it correctly handles all digits without affecting non-digit characters.

Exam trap

Python Institute often tests the distinction between literal string methods (`str.replace()`) and pattern-based methods (`re.sub()`), trapping candidates who assume `replace()` can interpret character ranges like `'0-9'` as a regex pattern.

How to eliminate wrong answers

Option A is wrong because `message.replace('0-9', 'X')` treats the string `'0-9'` as a literal substring to replace, not as a range of digits; it will only replace the exact sequence '0-9' if it appears in the message. Option C is wrong because `str.maketrans('0123456789', 'XXXXXXXXXX')` creates a translation table that maps each digit character to 'X', but `message.translate()` returns a new string with the replacements applied; while this would technically work, it is not the most direct or idiomatic approach for this task, and the question asks for the approach that 'correctly achieves this' — Option B is more standard and less error-prone. Option D is wrong because it uses a list comprehension with `c.isdigit()` to replace digits with 'X', which is functionally correct but is not a method of the string class; it is a valid Python expression but not a string method, and the question implies using a string method or a direct replacement approach.

297
Multi-Selecthard

Which THREE of the following statements about Python's 'with' statement are true? (Select exactly 3)

Select 3 answers
A.It can be used with any object that implements __enter__ and __exit__ methods.
B.It guarantees that the __exit__ method is called even if an exception occurs inside the block.
C.It can be used with multiple context managers separated by commas.
D.It eliminates the need for try/finally blocks for resource management.
E.It can only be used with file objects.
AnswersA, B, C

That's the context manager protocol.

Why this answer

Option A is correct because the 'with' statement in Python is designed to work with any object that implements the context management protocol, which consists of the __enter__ and __exit__ methods. This allows the 'with' statement to manage resources beyond just files, such as database connections, locks, or network sockets, as long as the object provides these two methods.

Exam trap

Python Institute often tests the misconception that the 'with' statement is only for file I/O, leading candidates to incorrectly select option E, while also testing the understanding that it simplifies but does not replace try/finally blocks, making option D a distractor for those who overestimate its capabilities.

298
Drag & Dropmedium

Drag and drop the steps to serialize a Python object to JSON using the json module 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

Serialization to JSON involves importing json, preparing data, using dumps for string or dump for file output.

Page 3

Page 4 of 7

Page 5

All pages