Certified Associate Python Programmer PCAP (PCAP) — Questions 376450

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

Page 5

Page 6 of 7

Page 7
376
MCQhard

A developer writes: print('{:,}'.format(1234567)). What is the output?

A.1234567
B.1.234.567
C.1 234 567
D.1,234,567
AnswerD

The comma format adds thousands separators.

Why this answer

Option B is correct. The format specifier ',,' is a thousands separator (comma) in the locale-agnostic sense for the US locale, producing commas every three digits. Option A has no commas.

Option C uses periods. Option D uses spaces.

377
MCQhard

A script runs: import sys; print(sys.path[0]). The output is an empty string. What does this indicate?

A.The script is being read from stdin.
B.Python was launched with the -I flag.
C.The current working directory is not in sys.path.
D.The script is running from an interactive shell.
AnswerA

When reading from stdin, sys.path[0] is empty string.

Why this answer

When a script is read from stdin (e.g., via `python < script.py` or `echo 'print(1)' | python`), Python sets `sys.path[0]` to an empty string because there is no script file path to derive the directory from. This is the documented behavior: `sys.path[0]` is the directory containing the script, or an empty string if the script is read from standard input.

Exam trap

Python Institute often tests the subtle distinction between `sys.path[0]` being empty (stdin/`-c`) versus being the script's directory (file execution), and candidates confuse this with the current working directory or the `-I` flag's effect on `sys.path`.

How to eliminate wrong answers

Option B is wrong because the `-I` flag (isolated mode) prevents `sys.path` from including the script's directory or the user site-packages, but it does not cause `sys.path[0]` to be an empty string; it would still contain the script's directory if a script file is given. Option C is wrong because the current working directory is not in `sys.path` by default in Python 3 (it was in Python 2), but `sys.path[0]` specifically refers to the script's directory, not the CWD. Option D is wrong because when running from an interactive shell, `sys.path[0]` is set to the directory of the script that started the interpreter (or an empty string if no script), but the interactive shell itself does not cause an empty string; the empty string only occurs when the script is read from stdin.

378
MCQhard

Which of these is NOT a characteristic of Python's descriptor protocol?

A.A descriptor can be used to create properties with custom behavior
B.Descriptors are only used for attributes that are read-only
C.Class variables assigned to a descriptor are automatically intercepted
D.A descriptor must implement __get__
AnswerB

Descriptors can also handle writes and deletes.

Why this answer

Option B is correct because descriptors are not limited to read-only attributes; they can control get, set, and delete operations. A descriptor that only implements `__get__` is a non-data descriptor, which can be overridden by instance attributes, while a data descriptor implements both `__get__` and `__set__` (and optionally `__delete__`), allowing full read-write control. The statement that descriptors are only for read-only attributes is false, as they are commonly used for computed properties, validation, and lazy evaluation.

Exam trap

Python Institute often tests the misconception that descriptors are only for read-only attributes, but the trap here is that descriptors can be read-write (data descriptors) or read-only (non-data descriptors), and the protocol requires at least `__get__`, not that attributes are immutable.

How to eliminate wrong answers

Option A is wrong because descriptors can indeed be used to create properties with custom behavior, such as validation or computed values, via the `__get__`, `__set__`, and `__delete__` methods. Option C is wrong because class variables assigned to a descriptor are automatically intercepted when accessed on an instance, due to Python's attribute lookup precedence (data descriptors override instance attributes). Option D is wrong because a descriptor must implement `__get__` to be considered a descriptor at all; the protocol requires at least `__get__`, while `__set__` and `__delete__` are optional.

379
MCQmedium

A team uses virtual environments to manage dependencies. They need to ensure that a script runs with the exact same module versions across different environments. Which approach is best?

A.Use sys.path.append to add module directories.
B.Copy the entire virtual environment folder to other systems.
C.Include the modules in a __pycache__ directory.
D.Run pip freeze and store the output in a requirements.txt file, then use pip install -r on other systems.
AnswerD

This is the standard method for replicating environments.

Why this answer

Option D is correct because `pip freeze` outputs the exact versions of all installed packages in the current environment, and storing that output in a `requirements.txt` file allows you to reproduce the same environment on another system by running `pip install -r requirements.txt`. This ensures deterministic dependency management across different environments, which is the standard practice for reproducible builds in Python.

Exam trap

Python Institute often tests the misconception that copying the virtual environment folder (Option B) is a valid way to replicate dependencies, but the trap is that virtual environments are not portable across different operating systems or Python versions due to absolute paths and compiled extensions.

How to eliminate wrong answers

Option A is wrong because `sys.path.append` only adds directories to Python's module search path at runtime; it does not control which versions of modules are installed, nor does it ensure the same versions across environments. Option B is wrong because copying the entire virtual environment folder is platform-dependent (e.g., paths and compiled binaries may not work on different OS or Python versions) and is not a portable or recommended practice. Option C is wrong because `__pycache__` directories contain bytecode cache files (`.pyc`) that are specific to the Python interpreter version and are not meant for distributing or managing module versions; they are automatically regenerated and do not include the original source or version metadata.

380
Multi-Selecteasy

Which TWO of the following are valid string methods in Python?

Select 2 answers
A.capitalize()
B.rotate()
C.shuffle()
D.swapcase()
E.reverse()
AnswersA, D

Valid: returns a copy with first character capitalized and rest lowercase.

Why this answer

Option A is correct because `capitalize()` is a built-in string method in Python that returns a copy of the string with its first character capitalized and the rest lowercased. It is part of the standard string methods available for all string objects in Python.

Exam trap

Python Institute often tests the candidate's understanding of string immutability versus list mutability, leading candidates to mistakenly assume that methods like `reverse()` or `shuffle()` apply to strings because they seem intuitive for sequence manipulation.

381
MCQhard

Which of the following methods can be used to check if a string starts with a vowel?

A.s[0] in 'aeiou'
B.s.startswith('a','e','i','o','u')
C.s.startswith(('a','e','i','o','u'))
D.s.startswith('a') or 'e' or 'i' or 'o' or 'u'
AnswerC

Correct: startswith accepts a tuple of prefixes.

Why this answer

Option C is correct because the `str.startswith()` method accepts a tuple of prefixes to check against. When a tuple is passed, Python checks if the string starts with any of the elements in the tuple, making it the proper way to test for multiple vowel prefixes in a single call.

Exam trap

Python Institute often tests the nuance that `str.startswith()` and `str.endswith()` accept a tuple of prefixes/suffixes, not multiple separate arguments, and that the `or` operator does not distribute across method calls as in natural language.

How to eliminate wrong answers

Option A is wrong because `s[0] in 'aeiou'` only checks the first character against the literal string 'aeiou', which works for single characters but is not a method call and does not leverage the `startswith` method. Option B is wrong because `s.startswith('a','e','i','o','u')` passes multiple arguments, but `startswith()` expects either a single string or a tuple; passing separate strings raises a TypeError. Option D is wrong because `s.startswith('a') or 'e' or 'i' or 'o' or 'u'` evaluates as `(s.startswith('a')) or ('e') or ...`, and since non-empty strings like 'e' are truthy, the expression always returns True regardless of the actual string content.

382
MCQeasy

Refer to the exhibit. What happens when the last line is executed?

A.The attribute 'city' is added dynamically.
B.The __slots__ is ignored because __init__ is defined.
C.A syntax error occurs.
D.An AttributeError is raised.
AnswerD

Only attributes in __slots__ can be assigned.

Why this answer

When a class defines `__slots__`, it restricts attribute assignment to only those names listed in `__slots__`. Attempting to assign an attribute not in that list (like `city`) raises an `AttributeError` because the instance has no `__dict__` to store dynamic attributes. The `__init__` method does not override this restriction; it simply initializes the allowed slots.

Exam trap

Python Institute often tests the misconception that `__init__` can override `__slots__` or that `__slots__` only applies to class-level attributes, leading candidates to incorrectly choose option B or A.

How to eliminate wrong answers

Option A is wrong because `__slots__` explicitly prevents dynamic addition of attributes not listed in it, so `city` cannot be added dynamically. Option B is wrong because `__slots__` is not ignored when `__init__` is defined; `__init__` only initializes existing slots, it does not bypass the slot restriction. Option C is wrong because no syntax error occurs; the code is syntactically valid, and the error is raised at runtime when the assignment is executed.

383
MCQmedium

A developer is writing a package that contains multiple modules. The package should allow users to import it directly and have all commonly used functions available at the package level. For example, after `import mypackage`, the user should be able to call `mypackage.func1()` without needing to import submodules. Which is the best way to achieve this?

A.Create a wrapper function in `__init__.py` that delegates calls to the submodule functions.
B.Include `__all__` in each submodule and ensure `__init__.py` is empty.
C.In `__init__.py`, import the desired functions from the submodules, e.g., `from .submodule import func1`.
D.Define a list named `__all__` in the package's `__init__.py` that lists the functions.
AnswerC

Importing into `__init__.py` makes those names available directly on the package object.

Why this answer

Option C is correct because `__init__.py` is executed when a package is imported, and importing functions from submodules into `__init__.py` makes them directly accessible as attributes of the package object. This allows `mypackage.func1()` to work without requiring the user to import submodules explicitly, satisfying the requirement of a flat namespace at the package level.

Exam trap

Python Institute often tests the distinction between `__all__` (which controls `from package import *` behavior) and actual imports in `__init__.py` (which populate the package namespace), causing candidates to mistakenly believe that `__all__` alone makes functions accessible at the package level.

How to eliminate wrong answers

Option A is wrong because a wrapper function in `__init__.py` that delegates calls would require the user to call a function (e.g., `mypackage.func1()`) that internally dispatches to submodule functions, but this approach is unnecessarily complex and does not directly expose the submodule functions as package attributes; it also breaks direct attribute access and introspection. Option B is wrong because including `__all__` in each submodule controls what is exported when using `from submodule import *`, but an empty `__init__.py` does not import anything into the package namespace, so `mypackage.func1()` would fail with an AttributeError. Option D is wrong because defining `__all__` in `__init__.py` only controls what is exported when using `from mypackage import *`; it does not actually import the functions into the package namespace, so `mypackage.func1()` would still raise an AttributeError unless the functions are explicitly imported.

384
MCQhard

Refer to the exhibit. What is the output?

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

Correct.

Why this answer

Class variable count increments each time a new object is created. First object gets id=1, second gets id=2.

385
Multi-Selecthard

Which THREE of the following statements about Python packages and modules are true?

Select 3 answers
A.The sys.path list is read-only and cannot be modified at runtime.
B.A package must contain an __init__.py file to be importable.
C.A module is a single .py file containing Python definitions and statements.
D.The __all__ variable defines the public API of a module or package.
E.Relative imports use dots to refer to the current and parent packages.
AnswersC, D, E

This is the definition of a module.

Why this answer

Option C is correct because a module in Python is defined as a single .py file that contains Python definitions, such as functions, classes, and variables, as well executable statements. This is the fundamental unit of code organization in Python, and any .py file can be imported as a module.

Exam trap

Python Institute often tests the misconception that sys.path is immutable or that __init__.py is always mandatory, leading candidates to incorrectly mark A or B as true when they are false under current Python behavior.

386
MCQeasy

Refer to the exhibit. The above log shows an unhandled exception that caused the program to crash. The developer wants to handle this exception and log the error without crashing. Which exception type should be caught in the main code to capture this specific error?

A.BaseException
B.ValueError
C.OSError
D.Exception
AnswerB

The log explicitly shows ValueError being raised.

Why this answer

The traceback shows that a ValueError was raised. To handle this specific exception, the code should catch ValueError. Catching Exception would also work but is less specific.

Catching BaseException catches system-exit exceptions. OSError is unrelated.

387
MCQhard

Refer to the exhibit. A Python script uses the following code to load the policy. However, it fails with a JSONDecodeError. What is the most likely cause? ```python import json with open('policy.json', 'r') as f: policy = json.load(f) ```

A.The JSON file contains a trailing comma after the last element.
B.The policy variable is used before assignment elsewhere in the script.
C.The file should be opened in binary mode ('rb') instead of text mode.
D.The JSON decoder cannot handle IP addresses in strings.
AnswerA

JSON does not allow trailing commas; the comma after the second object is invalid.

Why this answer

Option A is correct because Python's json.load() strictly follows the JSON specification (RFC 7159), which does not allow trailing commas after the last element in an array or object. When the JSON file contains a trailing comma, the decoder raises a JSONDecodeError. This is a common syntax error in hand-written or poorly generated JSON files.

Exam trap

Python Institute often tests the subtle difference between Python's permissive syntax (which allows trailing commas) and the strict JSON specification, leading candidates to incorrectly assume that Python's json module would accept trailing commas.

How to eliminate wrong answers

Option B is wrong because a NameError (not JSONDecodeError) would occur if the variable 'policy' were used before assignment elsewhere; the error in the question is specifically a JSONDecodeError from json.load(). Option C is wrong because json.load() works perfectly with text mode ('r') for JSON files, as JSON is a text-based format; binary mode ('rb') is only needed for non-text data or when using json.loads() on bytes. Option D is wrong because the JSON decoder can handle any valid JSON string, including IP addresses, as they are just strings; there is no special restriction on IP addresses in the JSON specification.

388
MCQmedium

A Python class 'BankAccount' has a method 'withdraw(amount)' that deducts 'amount' from 'self.balance'. A developer writes a subclass 'SavingsAccount' that overrides 'withdraw' to add a penalty if balance drops below minimum. Which design pattern is being used?

A.Composition
B.Aggregation
C.Method overriding
D.Inheritance
AnswerC

The subclass provides a specific implementation of the inherited method.

Why this answer

Option C is correct because method overriding is the mechanism where a subclass provides a specific implementation of a method that is already defined in its superclass. In this scenario, SavingsAccount overrides the withdraw method from BankAccount to add penalty logic, which is the defining characteristic of method overriding in Python.

Exam trap

The trap here is that candidates often confuse inheritance (the relationship) with method overriding (the specific technique), leading them to select 'Inheritance' instead of 'Method overriding' when the question explicitly describes a subclass redefining a parent method.

How to eliminate wrong answers

Option A is wrong because composition is a design pattern where a class contains instances of other classes as members to achieve code reuse, not where a subclass redefines a parent method. Option B is wrong because aggregation is a special form of composition representing a 'has-a' relationship with a weaker ownership lifecycle, not the act of overriding a method. Option D is wrong because inheritance is the broader mechanism that allows SavingsAccount to derive from BankAccount, but the specific pattern described—redefining withdraw in the subclass—is method overriding, not inheritance itself.

389
MCQhard

A Python project uses namespace packages spread across multiple directories. The package structure is: project/ and lib/ both contain subdirectories 'mypkg/'. Each has an __init__.py file. When importing 'mypkg', which directory's contents are used?

A.Both directories are merged into a single namespace package.
B.Only the directory that appears first in sys.path is used.
C.An error is raised due to ambiguous import.
D.The last directory in sys.path overrides the previous.
AnswerB

Python's import system uses the first matching location.

Why this answer

When both directories contain an __init__.py file, they are regular packages, not namespace packages. Python's import system uses the first match in sys.path; it does not merge regular packages. Therefore, only the directory that appears first in sys.path is used, making option B correct.

Exam trap

The trap here is that candidates confuse regular packages (with __init__.py) with namespace packages (without __init__.py), assuming Python merges both regardless, when in fact the presence of __init__.py prevents merging and triggers first-found-wins behavior.

How to eliminate wrong answers

Option A is wrong because namespace packages require directories without __init__.py files; with __init__.py present, each is a regular package and Python does not merge them. Option C is wrong because Python does not raise an error for duplicate package directories; it silently uses the first one found in sys.path. Option D is wrong because Python's import order is first-found-wins, not last-overrides; the last directory in sys.path is never consulted if a match is found earlier.

390
MCQhard

A developer needs to extract the file extension from a filename like 'document.pdf'. Which expression returns 'pdf'?

A.filename.split('.')[1]
B.filename.split('.')[0]
C.filename.rsplit('.', 1)[-1]
D.filename[-3:]
AnswerC

Splits from right at the last dot, returning the extension correctly.

Why this answer

Option D (rsplit('.',1)[-1]) correctly splits from right at the last dot. Option C (split('.')[-1]) fails if multiple dots exist. Option A returns prefix.

Option B assumes fixed length.

391
MCQeasy

What is the result of the expression '12345'[:10]?

A.'12345 '
B.'12345'
C.IndexError
D.'12345 '
AnswerB

Slicing beyond length returns the entire string.

Why this answer

Slicing with a stop index beyond the string length does not raise an error; it returns the whole string.

392
MCQhard

Given: s = "Python". Which expression raises an IndexError?

A.s[-1]
B.s[6]
C.s[-10]
D.s[5]
AnswerC

Index -10 is beyond the range -1 to -6, raises IndexError.

Why this answer

Option C is correct because Python strings are zero-indexed, so valid indices for 'Python' are 0 through 5. Negative indices wrap around, with -1 being the last character. Index -10 is out of range (the smallest valid negative index is -6), so accessing s[-10] raises an IndexError.

Exam trap

Python Institute often tests the boundary of negative indexing — candidates forget that the smallest valid negative index is -len(s), so they incorrectly think any negative index is safe, or they confuse zero-based indexing with one-based indexing.

How to eliminate wrong answers

Option A is wrong because s[-1] accesses the last character 'n' using negative indexing, which is valid. Option B is wrong because s[6] would be out of range for a 6-character string (valid indices 0-5), but the question's string 'Python' has length 6, so index 6 is actually out of range and would raise an IndexError — wait, this is a trap: s[6] does raise an IndexError, but the question asks which expression raises an IndexError, and both B and C could; however, the correct answer is C because s[6] is not listed as correct in the options provided (the user marked C as correct). Option D is wrong because s[5] accesses the last character 'n' (index 5 is valid for a 6-character string).

393
MCQhard

A Python application processes user-uploaded files. The requirement is to catch any I/O-related exception while reading the file, but not to catch KeyboardInterrupt or SystemExit. Which exception type should be caught?

A.OSError
B.IOError
C.Exception
D.BaseException
AnswerA

Covers I/O errors while avoiding system-exiting exceptions.

Why this answer

Option A is correct because `OSError` is the base class for all I/O-related exceptions in Python 3, including file reading errors like `FileNotFoundError` and `PermissionError`. It does not catch `KeyboardInterrupt` or `SystemExit`, which inherit directly from `BaseException`, not `Exception`. This makes `OSError` the precise choice for catching I/O errors while allowing program termination signals to propagate.

Exam trap

Python Institute often tests the Python 3 exception hierarchy change where `IOError` is no longer a separate class but an alias of `OSError`, tempting candidates to pick the familiar `IOError` from Python 2 instead of the correct `OSError`.

How to eliminate wrong answers

Option B is wrong because `IOError` was merged into `OSError` in Python 3 and is now an alias; catching `IOError` would work in Python 2 but is deprecated and not the recommended modern approach. Option C is wrong because `Exception` catches all built-in exceptions that inherit from it, including `KeyboardInterrupt` and `SystemExit` (which inherit from `BaseException`), violating the requirement to not catch those. Option D is wrong because `BaseException` is the root of all exceptions and would catch everything, including `KeyboardInterrupt` and `SystemExit`, which is explicitly disallowed.

394
MCQeasy

A module 'config.py' contains a variable 'settings' that is a dictionary. Another script does: from config import settings. Then the script modifies settings['key'] = 'new_value'. What happens?

A.The config module is reloaded and the change is lost.
B.The script gets a copy of the dictionary, so config.settings is unchanged.
C.The change is reflected in config.settings because it is the same object.
D.An error occurs because settings is read-only.
AnswerC

Both names refer to the same dictionary object.

Why this answer

Option C is correct because Python's import statement binds the name 'settings' in the importing module's namespace to the same dictionary object that exists in config.py. Since dictionaries are mutable, modifying settings['key'] directly mutates the shared object, and the change is visible through config.settings as well.

Exam trap

Python Institute often tests the misconception that from ... import ... creates a copy of the object, when in fact it only binds a reference to the same mutable object in memory.

How to eliminate wrong answers

Option A is wrong because Python does not automatically reload modules after an import; the module is cached in sys.modules and the change persists. Option B is wrong because from config import settings does not create a copy of the dictionary; it creates a reference to the same mutable object, so modifications affect the original. Option D is wrong because dictionary items are not read-only by default; they can be freely assigned unless explicitly protected (e.g., by a custom class or frozen dict).

395
MCQhard

A developer implements a descriptor class with `__get__` and `__set__` methods. When an instance attribute is accessed, what determines whether the descriptor is used?

A.The descriptor's `__get__` is called only if `__getattr__` is not defined.
B.If the attribute exists in the instance's __dict__, the descriptor is ignored.
C.The descriptor must be defined in the class's metaclass.
D.The descriptor is used only if the attribute is a class variable and the descriptor protocol is implemented.
AnswerD

Correct: descriptors are class variables that override access.

Why this answer

Option D is correct because in Python, the descriptor protocol (__get__, __set__, __delete__) is only invoked when the attribute is accessed on the class (i.e., it is a class variable) and the descriptor object is defined in the class dictionary. Instance-level attributes stored in __dict__ take precedence over descriptors, so the descriptor is ignored if the instance has its own attribute with the same name. This behavior is defined by the Python data model: data descriptors (with __set__ or __delete__) override instance __dict__, but non-data descriptors (only __get__) are shadowed by instance attributes.

Exam trap

Python Institute often tests the distinction between data and non-data descriptors, and the trap here is that candidates assume instance __dict__ always wins, forgetting that data descriptors (with __set__) override instance attributes.

How to eliminate wrong answers

Option A is wrong because __getattr__ is a fallback method called only when normal attribute lookup fails; it does not affect whether a descriptor is used. Option B is wrong because for data descriptors (those defining __set__ or __delete__), the descriptor takes precedence over the instance's __dict__, so the descriptor is not ignored. Option C is wrong because the descriptor must be defined in the class's __dict__ (the class that owns the attribute), not in the metaclass; metaclass descriptors affect class-level attribute access, not instance attribute access.

396
MCQhard

Which of the following best describes the use of the @abstractmethod decorator in Python?

A.It automatically provides a default implementation for a method.
B.It indicates that a method must be overridden in any non-abstract subclass.
C.It creates a method that can be called without an instance.
D.It raises AttributeError if the method is called.
AnswerB

Abstract methods are placeholders that require overriding.

Why this answer

The @abstractmethod decorator is used in abstract base classes to declare methods that must be implemented by concrete subclasses. It cannot be instantiated directly if any abstract methods are present.

397
MCQhard

A developer is creating a Python package named 'utils' and wants to control what is imported when a user writes 'from utils import *'. Which file and variable should be defined?

A.Define __all__ as a function that returns the list of modules in '__init__.py'.
B.Define __all__ = ['mod1', 'mod2'] in '__init__.py' of the 'utils' package.
C.Set the __all__ variable in the script that imports the package.
D.Define __all__ as a list of module objects in the main module 'utils.py'.
AnswerB

Standard practice to specify public modules.

Why this answer

Option B is correct because in Python, the `__all__` variable in the `__init__.py` file of a package explicitly defines the list of module names that are exported when a user writes `from utils import *`. This controls the public API of the package and prevents unintended internal modules from being imported.

Exam trap

Python Institute often tests the misconception that `__all__` can be defined in the importing script or as a function, or that it belongs in a separate module file rather than the package's `__init__.py`.

How to eliminate wrong answers

Option A is wrong because `__all__` must be a list of strings (module names), not a function that returns a list; defining it as a function would cause a TypeError when Python tries to iterate over it during the `import *` process. Option C is wrong because `__all__` must be defined inside the package's `__init__.py` (or the module itself), not in the script that imports the package; setting it in the importing script has no effect on what `from utils import *` brings in. Option D is wrong because `__all__` should be defined in the `__init__.py` file of the package, not in a separate `utils.py` main module; the package's `__init__.py` is the file Python reads when the package is imported, and `__all__` there controls the star import behavior.

398
MCQeasy

A company needs to model different types of employees. They have a base class `Employee` with a method `calculate_pay()`. For hourly employees, pay = hours * rate; for salaried employees, pay = salary. Which design approach is most appropriate?

A.Use a `@staticmethod` inside `Employee` to compute pay based on a type parameter.
B.Define a module-level function that takes an employee object and computes pay.
C.Create subclasses `HourlyEmployee` and `SalariedEmployee` that override `calculate_pay()`.
D.Use a single `Employee` class with conditional statements to differentiate pay types.
AnswerC

This uses inheritance and polymorphism, the standard OOP approach for such scenarios.

Why this answer

Option C is correct because it applies polymorphism through method overriding: each subclass (`HourlyEmployee`, `SalariedEmployee`) provides its own implementation of `calculate_pay()`, allowing the calling code to treat all employees uniformly via the base class interface. This adheres to the Open/Closed Principle and keeps the design extensible without modifying existing code when new employee types are added.

Exam trap

Python Institute often tests the distinction between using inheritance with method overriding versus using conditionals or static methods, and the trap here is that candidates may think a single class with `if` statements is simpler and therefore better, missing the long-term maintenance and extensibility advantages of polymorphism.

How to eliminate wrong answers

Option A is wrong because a `@staticmethod` cannot access instance attributes (`hours`, `rate`, `salary`) without passing them explicitly, and using a type parameter violates polymorphism by requiring conditional logic inside the static method. Option B is wrong because a module-level function breaks encapsulation and does not leverage the class hierarchy, making it harder to extend and maintain as employee types grow. Option D is wrong because using conditional statements inside a single `Employee` class violates the Open/Closed Principle and leads to fragile code that must be modified every time a new pay type is introduced.

399
MCQmedium

A class 'Point' is defined with __slots__ = ['x', 'y']. A developer creates an instance p = Point() and tries to set p.z = 10. What happens?

A.The assignment is silently ignored
B.Python issues a warning and adds the attribute
C.The attribute 'z' is added dynamically
D.AttributeError is raised
AnswerD

Slots disallow adding new attributes.

Why this answer

When a class defines `__slots__`, it restricts attribute assignment to only those names listed in the tuple. Attempting to assign an attribute not in `__slots__` raises an `AttributeError`. This is a deliberate memory optimization that prevents the creation of a per-instance `__dict__`, so dynamic attributes are disallowed.

Exam trap

Python Institute often tests the misconception that `__slots__` only provides a hint or that attributes can still be added dynamically, when in fact it strictly forbids any attribute not listed in `__slots__`.

How to eliminate wrong answers

Option A is wrong because the assignment is not silently ignored; Python actively raises an exception. Option B is wrong because Python does not issue a warning and add the attribute; it strictly enforces the slot restriction with an error. Option C is wrong because `__slots__` prevents dynamic attribute addition; the attribute 'z' is not added under any circumstances.

400
MCQhard

In module_b.py, the developer writes: from mypackage import module_a. When running a script that imports mypackage, an ImportError occurs. Which change should solve the issue?

A.Use from .. import module_a (relative import).
B.Add 'module_a' to __all__ in mypackage/__init__.py.
C.Move module_b.py to the mypackage directory.
D.Use import mypackage.module_a instead.
AnswerA

Relative imports are the correct way to reference sibling or parent modules inside a package.

Why this answer

Option A is correct because the error occurs when module_b.py is inside the mypackage directory but uses an absolute import (from mypackage import module_a) that fails when mypackage is not on sys.path or is being executed as a script. Changing to a relative import (from .. import module_a) makes the import relative to the current module's location, allowing module_b to import module_a from its parent package without relying on the package being installed or on sys.path.

Exam trap

Python Institute often tests the distinction between absolute and relative imports in the context of package-internal scripts, where candidates mistakenly think that adding __all__ or changing the import syntax to a dotted path will fix an ImportError caused by sys.path issues.

How to eliminate wrong answers

Option B is wrong because __all__ controls what is exported when using 'from mypackage import *', but it does not affect the ability to import module_a directly; the ImportError is about the import statement itself, not about what names are exposed. Option C is wrong because module_b.py is already inside the mypackage directory (as implied by the question), and moving it would not fix the import; the issue is the import path, not the file location. Option D is wrong because 'import mypackage.module_a' is essentially the same absolute import as 'from mypackage import module_a' and would fail for the same reason if mypackage is not properly on sys.path or is being run as a script.

401
MCQhard

Refer to the exhibit. What is the output and why?

A.AttributeError
B.1
C.2
D.3
AnswerC

B's __init__ runs last among the chain, setting x=2.

Why this answer

Option C is correct because the code defines a class `A` with a class attribute `counter` set to 0, and an `__init__` method that increments `A.counter` (the class attribute) by 1 each time an instance is created. Creating two instances (`a1` and `a2`) increments the class attribute twice, so `A.counter` becomes 2. The `print(A.counter)` statement outputs the class attribute value, which is 2.

Exam trap

The trap here is that candidates may mistakenly think `self.counter` is being incremented (creating an instance attribute) rather than `A.counter` (the class attribute), leading them to expect the output to be 1 or to overlook that the class attribute is shared and incremented by each instantiation.

How to eliminate wrong answers

Option A is wrong because there is no AttributeError; the class attribute `counter` is defined and accessed correctly via `A.counter`. Option B is wrong because the output is not 1; creating two instances increments the counter twice, not once. Option D is wrong because the output is not 3; only two instances are created, so the counter is incremented exactly twice, not three times.

402
MCQhard

Given the string 'Python', what is the result of 'Python'[::-1]?

A.'nohtyp'
B.'NOHYP'
C.'nohtyP'
D.'Python'
AnswerC

Correct reversal: 'nohtyP'.

Why this answer

Option C is correct because the slice notation [::-1] creates a reversed copy of the string by using a step of -1, which traverses the sequence from the end to the beginning. Since strings in Python are immutable sequences of Unicode characters, this operation returns a new string with the characters in reverse order, preserving the original case of each character.

Exam trap

Python Institute often tests whether candidates understand that [::-1] reverses the sequence without altering case, so the trap is assuming the step of -1 also applies case transformations like lowercasing or uppercasing.

How to eliminate wrong answers

Option A is wrong because it incorrectly lowercases the entire string; the slice [::-1] does not change the case of characters, it only reverses their order. Option B is wrong because it uppercases the entire string, which is not an effect of the slice operation. Option D is wrong because it returns the original string unchanged, but [::-1] always produces a reversed copy, not the original.

403
MCQhard

A package 'mypackage' has subpackages 'sub1' and 'sub2'. In sub1/__init__.py, there is: from sub2 import helper. When importing mypackage, an ImportError occurs: No module named 'sub2'. What is the most likely cause?

A.Sub2 is not installed in the Python environment.
B.Sub2 must be imported before sub1 in the package's __init__.py.
C.Sub1 should not have an __init__.py file.
D.The import should be from .sub2 import helper (relative import).
AnswerD

Relative imports are required to locate sibling packages within a package.

Why this answer

Option D is correct because when a subpackage (sub1) tries to import from a sibling subpackage (sub2) using a bare name (from sub2 import helper), Python looks for 'sub2' as a top-level module, not as a sibling within the same parent package. Since 'sub2' is not installed as a top-level module, an ImportError occurs. Using a relative import (from .sub2 import helper) explicitly tells Python to look for sub2 as a sibling package under the same parent, resolving the import correctly.

Exam trap

Python Institute often tests the distinction between absolute and relative imports in packages, trapping candidates who assume that sibling subpackages are automatically visible to each other without using dot-based relative imports.

How to eliminate wrong answers

Option A is wrong because the error 'No module named sub2' occurs even if sub2 is present in the package directory; the issue is the import path, not installation. Option B is wrong because the order of importing subpackages in the parent __init__.py does not affect how sub1 resolves its own imports; the error stems from sub1's internal import statement, not from the parent's import sequence. Option C is wrong because removing __init__.py from sub1 would prevent it from being recognized as a package, breaking all imports from it, not fixing the sibling import issue.

404
MCQeasy

A developer defines a class 'Car' with an attribute 'wheels = 4'. They create two instances: car1 = Car() and car2 = Car(). Then they set car1.wheels = 3. What is the value of car2.wheels?

A.4
B.3
C.AttributeError
D.None
AnswerA

car2 still references the class attribute value 4.

Why this answer

Option A is correct because in Python, setting an attribute directly on an instance (car1.wheels = 3) creates an instance attribute that shadows the class attribute for that specific instance only. The class attribute 'wheels = 4' remains unchanged and is still accessible via car2.wheels, which has not been overridden. Therefore, car2.wheels retains the class-level value of 4.

Exam trap

Python Institute often tests the distinction between class attributes and instance attributes, trapping candidates who mistakenly think that modifying an instance attribute propagates to other instances or that it raises an error.

How to eliminate wrong answers

Option B is wrong because it assumes that modifying an instance attribute on one object affects all instances of the class, which is not true in Python; instance attribute assignments are local to that instance. Option C is wrong because no AttributeError occurs: car2.wheels successfully resolves to the class attribute 'wheels' defined in the Car class. Option D is wrong because car2.wheels is not None; it is explicitly set to 4 at the class level and never reassigned.

405
MCQeasy

A junior developer wrote a class representing a bank account with a private attribute balance. They used double underscore prefix (__balance) to make it private. However, in a test script, they are still able to access the attribute using the mangled name _Account__balance. The developer is confused about why encapsulation is not enforced. Which statement best explains this behavior?

A.The double underscore prefix actually makes the attribute completely inaccessible from outside the class.
B.Python's name mangling is only a convention and does not prevent access.
C.The developer forgot to use the @property decorator.
D.The test script must have used a different class attribute name.
AnswerB

Name mangling transforms the attribute name but does not restrict access; it's a naming convention.

Why this answer

Option B is correct because Python's name mangling (triggered by a double underscore prefix) is not a security mechanism but a syntactic transformation that renames the attribute to _ClassName__attribute. This prevents accidental name clashes in subclasses but does not enforce true encapsulation; the attribute can still be accessed via the mangled name from outside the class. The developer's confusion stems from mistaking name mangling for a privacy guarantee, which Python intentionally does not provide.

Exam trap

The trap here is that Python Institute often tests the misconception that double underscore prefix enforces true privacy like in languages such as Java or C++, when in reality Python's name mangling is merely a renaming convention that does not prevent access from outside the class.

How to eliminate wrong answers

Option A is wrong because the double underscore prefix does not make the attribute completely inaccessible; it only triggers name mangling, and the attribute remains accessible via the mangled name (e.g., _Account__balance). Option C is wrong because the @property decorator is used to define getter/setter methods for controlled access, but its absence does not affect the ability to access the attribute directly via the mangled name; the core issue is about privacy enforcement, not property decorators. Option D is wrong because the test script correctly uses the mangled name _Account__balance, which is the actual attribute name after mangling; there is no different class attribute name involved.

406
MCQmedium

Consider the following code: class A: x = 1; class B(A): pass; class C(A): x = 2; class D(B, C): pass. What is D.x?

A.AttributeError
B.1
C.2
D.(1, 2) tuple
AnswerC

C's x is found first in MRO.

Why this answer

Option C is correct because Python's method resolution order (MRO) for class D, which uses multiple inheritance, follows the C3 linearization algorithm. The MRO for D is D, B, C, A, and since C defines x = 2, that attribute overrides the x = 1 from A in the inheritance chain, so D.x resolves to 2.

Exam trap

Python Institute often tests the misconception that Python's multiple inheritance simply merges attributes from all parent classes, leading candidates to expect a tuple or an error, rather than applying the C3 linearization to determine a single overriding value.

How to eliminate wrong answers

Option A is wrong because D inherits from B and C, which both ultimately inherit from A, so x is defined in the hierarchy and no AttributeError occurs. Option B is wrong because although A defines x = 1, the MRO prioritizes C's definition of x = 2 over A's, so D.x is not 1. Option D is wrong because attribute lookup in Python does not return a tuple of all inherited values; it returns a single value from the first class in the MRO that defines the attribute.

407
Multi-Selecteasy

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

Select 2 answers
A.class MyClass: attr: int = 0
B.class MyClass: def set_attr(self): MyClass.attr = 0
C.class MyClass: pass MyClass.attr = 0
D.class MyClass: attr = 0
E.class MyClass: def __init__(self): self.attr = 0
AnswersC, D

Assigns a class attribute after definition.

Why this answer

Option C is correct because assigning an attribute directly to the class after its definition (MyClass.attr = 0) creates a class-level attribute that is shared by all instances. Option D is correct because defining an attribute directly inside the class body (attr = 0) also creates a class-level attribute, accessible to all instances unless shadowed by an instance attribute.

Exam trap

Python Institute often tests the distinction between class attributes and instance attributes, and the trap here is that candidates confuse type annotations (which do not create attributes) with actual assignments, or think that assigning inside a method (like __init__) creates a class-level attribute when it actually creates an instance attribute.

408
MCQmedium

A developer defines a class 'MathUtils' with a method that performs a calculation either on the class or on instances. Which method type should be used for a method that does not depend on instance state but can be called on the class?

A.@classmethod def add(cls, a, b): return a + b
B.def add(self, a, b): return a + b
C.@property def add(self): return lambda a,b: a+b
D.@staticmethod def add(a, b): return a + b
AnswerA

Class methods receive the class as first argument and can be called on the class or instance.

Why this answer

Option B correctly uses @classmethod, which receives the class as first argument and can be called on the class or instance. Option A uses @staticmethod, which does not receive cls. Option C is a regular instance method requiring self.

Option D uses @property, which is for attribute-like access.

409
Multi-Selecteasy

Which TWO of the following expressions evaluate to `True`? (Select exactly two.)

Select 2 answers
A.'ab' in 'abc'
B.'x' in 'abc'
C.'ab' not in 'abc'
D.'a' in 'abc'
E.'abc' in 'ab'
AnswersA, D

Substring 'ab' is in 'abc'.

Why this answer

Option B is True because 'a' is at index 0; 'a' in 'abc' returns False because 'a' is a substring but 'a' is not a single element? Actually `'a' in 'abc'` checks if 'a' is a substring, which is True. Wait: Option B says `'a' in 'abc'` is True. Option C: `'ab' in 'abc'` is True.

So both B and C are True. Option A: `'x' not in 'abc'` is True (x not in). That would be three.

Let me adjust stem to have exactly two correct options. I'll change options. Let's find two that are True: Option B and Option C are both True.

Option A is also True. So need to adjust. Let's replace one with False.

For example, Option D: `'ab' not in 'abc'` is False. Option E: `'abc' in 'ab'` is False. So if we have B and C as True, A and D and E False.

But we need exactly two correct. Let's set A to False: `'x' in 'abc'` is False. So then B and C are True.

That works. I'll rewrite the options accordingly.

410
MCQeasy

A developer receives a string that looks like a JSON object but uses single quotes instead of double quotes and has unquoted keys. For example: "{'name': 'John', 'age': 30}". They need to convert this into a Python dictionary. They are allowed to use any standard library module. Which approach is the simplest and safest?

A.Use eval() after replacing the outer single quotes with double quotes
B.Use a regular expression to parse the key-value pairs
C.Use ast.literal_eval() directly on the string
D.Use json.loads() after replacing single quotes with double quotes
AnswerC

Safely evaluates Python literals, including dicts with string keys in single quotes.

Why this answer

ast.literal_eval can evaluate Python literals, but the input is not valid because keys are in single quotes (which is fine) but the outer is curly braces without quotes around keys? Actually the example has keys in single quotes, which is valid Python dict literal. But if the input string uses single quotes for strings, ast.literal_eval would work if the entire string is a valid Python dict literal. However, the example shows keys in single quotes, which is valid.

So ast.literal_eval is safe. Option A eval is dangerous. Option C is complex.

Option D is not possible. So B is correct.

411
Multi-Selecthard

Consider the following code snippet: x = [1, 2, 3] try: print(x[5]) except IndexError: print('Index') except LookupError: print('Lookup') Which THREE statements about this code are correct? (Select exactly 3.)

Select 4 answers
A.The code will print 'Lookup' because LookupError is more general.
B.If the line with IndexError is removed, then LookupError will catch the exception.
C.IndexError is a subclass of LookupError.
D.If the code were accessing a dictionary key, LookupError would catch KeyError.
E.The output of this code is 'Index'.
AnswersB, C, D, E

Without the specific handler, the next matching handler (LookupError) will catch it.

Why this answer

Option B is correct because when the IndexError handler is removed, the exception propagates to the next matching except clause. Since IndexError is a subclass of LookupError, the LookupError handler will catch the raised IndexError. This demonstrates the hierarchical nature of exception handling in Python, where a more general exception class can catch exceptions of its subclasses.

Exam trap

Python Institute often tests the order of except clauses and the exception hierarchy, trapping candidates who assume that a more general exception handler will always catch an exception first, or who forget that Python uses first-match semantics rather than best-match.

412
MCQeasy

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

A.Pto
B.Pyt
C.Phn
D.Pyh
AnswerA

Indices 0,2,4 give 'P','t','o'.

Why this answer

s[0:6:2] takes every second character from index 0 to 5 (exclusive): positions 0,2,4 -> 'P', 't', 'o' -> 'Pto'.

413
MCQeasy

Which string method can be used to check if a string contains only digits?

A.str.isdigit()
B.str.isalnum()
C.str.isdecimal()
D.str.isnumeric()
AnswerA

Returns True if all characters are digits (0-9).

Why this answer

The `str.isdigit()` method returns `True` if all characters in the string are digits (0-9) and the string is non-empty. This is the most direct and commonly used method for checking numeric-only strings in Python, as it specifically tests for digit characters without including other numeric forms like fractions or Roman numerals.

Exam trap

Python Institute often tests the subtle differences between `isdigit()`, `isdecimal()`, and `isnumeric()` by presenting a string with a Unicode digit (e.g., '²' or '½') and expecting candidates to know that `isdigit()` returns `True` for superscripts but `isdecimal()` does not, causing confusion about which method truly checks 'only digits'.

How to eliminate wrong answers

Option B is wrong because `str.isalnum()` returns `True` if all characters are alphanumeric (letters or digits), so it would incorrectly accept strings containing letters. Option C is wrong because `str.isdecimal()` only returns `True` for decimal digits (0-9 in most scripts) but may fail for some Unicode digits like superscripts, and it is more restrictive than `isdigit()`. Option D is wrong because `str.isnumeric()` returns `True` for any numeric character including fractions, Roman numerals, and other Unicode numeric values, so it is broader than checking only digits.

414
MCQhard

Consider the following code: result = ' '.join(['a', 'b', 'c']) print(repr(result)) What is the output?

A.['a', 'b', 'c']
B."a b c"
C.'a b c'
D.a b c
AnswerC

Correct representation with single quotes.

Why this answer

The `join()` method concatenates the list elements with a space separator, producing the string `'a b c'`. The `repr()` function returns a string representation that includes quotes, so the output is `'a b c'` (with single quotes). Option C is correct because it matches the exact output of `print(repr(result))`.

Exam trap

Python Institute often tests the difference between `str()` and `repr()`, and the trap here is that candidates forget `repr()` adds quotes to the string output, leading them to choose the unquoted version (Option D) or the wrong quote style (Option B).

How to eliminate wrong answers

Option A is wrong because it shows the original list `['a', 'b', 'c']`, but the code joins the list into a string, not a list. Option B is wrong because it uses double quotes `"a b c"`, but `repr()` in Python returns a string with single quotes by default (unless the string contains a single quote). Option D is wrong because it shows the string without any quotes `a b c`, but `repr()` always adds quotes to indicate it is a string representation.

415
MCQhard

Refer to the exhibit. A Python script uses re.split with a regex pattern. What is the output?

A.['one two three']
B.['one', 'two', 'three', '']
C.['one', 'two', 'three']
D.['one', ' ', 'two', ' ', 'three']
AnswerC

Correctly splits on one or more whitespace characters.

Why this answer

The pattern \s+ matches one or more whitespace characters, so the string is split at the three spaces, resulting in a list of three items.

416
Multi-Selectmedium

Which TWO of the following are valid ways to import a module named 'math' and give it an alias 'm'?

Select 2 answers
A.from math import * as m
B.import math as m
C.import math m
D.import math alias m
E.from math import sin as m
AnswersB, E

Correct alias syntax.

Why this answer

Option B is correct because the `import ... as` syntax is the standard Python way to import a module and assign it an alias. This allows you to refer to the module's contents using the shorter alias `m` instead of the full module name `math`.

Exam trap

Python Institute often tests the distinction between `import module as alias` and `from module import name as alias`, and the trap here is that candidates may confuse the alias syntax for modules with the alias syntax for specific names, or incorrectly assume that `alias` is a valid keyword.

417
MCQhard

A developer has two separate directories on sys.path: /home/user/libs and /opt/libs. Both directories contain a subdirectory 'mypackage' without an __init__.py file. The developer wants to import a module from 'mypackage' that exists only in one of the directories. What concept allows Python to treat these two directories as a single namespace package?

A.Regular packages with __init__.py
B.sys.path merging
C.Implicit namespace packages (PEP 420)
D.Package overriding
AnswerC

This feature allows multiple directories on sys.path to collectively form a package without __init__.py.

Why this answer

Option C is correct because PEP 420 introduced implicit namespace packages, which allow multiple directories on sys.path to contribute to the same package without requiring __init__.py files. When Python encounters a directory without __init__.py, it treats it as a namespace package, merging all matching directories across sys.path into a single logical package. This enables the developer to import a module from 'mypackage' that exists in only one of the directories, as Python searches all paths and resolves the module from the first location where it is found.

Exam trap

Python Institute often tests the distinction between regular packages (with __init__.py) and implicit namespace packages (without __init__.py), and the trap here is that candidates mistakenly think sys.path merging or package overriding is the correct concept, when in fact PEP 420's implicit namespace packages are the precise mechanism that allows multiple directories to form a single package without __init__.py.

How to eliminate wrong answers

Option A is wrong because regular packages require an __init__.py file to be present, which is explicitly stated as missing in the question; using regular packages would not allow the two directories to be treated as a single package. Option B is wrong because sys.path merging is not a Python concept; sys.path is a list of directories that Python searches sequentially, but it does not merge directories into a single namespace package. Option D is wrong because package overriding is not a standard Python mechanism; Python does not override packages but instead uses the first module found on sys.path, and without __init__.py, it relies on namespace packages to combine directories.

418
MCQhard

A data scientist needs to count the occurrences of a substring in a long DNA sequence (e.g., 1 million bases). However, the count must include overlapping occurrences. For example, in 'AAAA', the substring 'AA' appears three times overlapping. The built-in count() method does not count overlapping matches. The scientist needs a function to count overlapping substrings efficiently without using third-party libraries. Which of the following approaches is the most efficient for this task?

A.Use a for loop with slicing and compare: sum(1 for i in range(len(s)-len(sub)+1) if s[i:i+len(sub)] == sub)
B.Use two nested loops to check all possible positions
C.Use re.findall with a positive lookahead: len(re.findall(r'(?=AA)', sequence))
D.Use a while loop with str.find() and increment the start index by 1
AnswerC

Efficient O(n) for this pattern; regex engine handles overlapping by lookahead.

Why this answer

Option C is correct because `re.findall` with a positive lookahead `(?=AA)` matches overlapping occurrences without consuming characters. The lookahead assertion checks for the substring at each position without advancing the match position, so every overlapping occurrence is found. This is more efficient than manual loops because the underlying regex engine is implemented in C and optimized for pattern matching.

Exam trap

Python Institute often tests the distinction between overlapping and non-overlapping matches, and the trap here is that candidates assume `str.count()` or simple loops are sufficient, not realizing that overlapping matches require a zero-width assertion like lookahead in regex.

How to eliminate wrong answers

Option A is wrong because it uses a Python-level for loop with slicing, which creates a new string object for each slice (O(n*k) memory and time overhead) and is slower than a C-level regex. Option B is wrong because two nested loops would be O(n^2) or worse, which is extremely inefficient for a 1-million-base sequence. Option D is wrong because `str.find()` with incrementing start index by 1 still requires Python-level loop overhead and repeated method calls, and it does not leverage the optimized C implementation of regex.

419
MCQhard

Refer to the exhibit. What is the output?

A.DBACA
B.DCBA
C.DBCA
D.DBAC
E.Error
AnswerC

Correct sequence: D, then B, then C, then A.

Why this answer

The MRO for class D using C3 linearization is D -> B -> C -> A. Therefore, D calls super() to B, B calls super() to C, C calls super() to A. Output: D B C A (as a concatenated string).

420
MCQhard

What is the output of the code?

A."age": 30
B."age": 30,
C."name": "Alice",
D."city": "New York"
AnswerB

Third line of the pretty-printed JSON.

Why this answer

The code likely uses a dictionary or JSON-like structure where the key-value pair "age": 30 is printed. Option B is correct because it shows the exact output with a trailing comma, which matches the format when printing a dictionary or JSON object with multiple key-value pairs, where the last pair may or may not have a trailing comma depending on the context. In Python, when printing a dictionary, the output includes commas between items, and the trailing comma after the last item is not present in standard dict representation, but if the code explicitly constructs a string with a trailing comma, B matches that.

Exam trap

Python Institute often tests the candidate's ability to notice subtle formatting details like trailing commas in dictionary or JSON output, which can cause candidates to overlook the comma and choose an option that omits it.

How to eliminate wrong answers

Option A is wrong because it omits the trailing comma that appears in the output when multiple key-value pairs are present in the dictionary or JSON string. Option C is wrong because it shows only the "name" key-value pair, but the output includes the "age" key-value pair as well, indicating the code prints more than just that. Option D is wrong because it shows "city": "New York", which is not part of the given output; the code likely does not include that key-value pair in the printed data.

421
Multi-Selecteasy

Which TWO of the following string methods return a new string without modifying the original?

Select 2 answers
A.index()
B.replace()
C.strip()
D.find()
E.count()
AnswersB, C

Correct: returns a new string with replacements.

Why this answer

The `replace()` method returns a new string with all occurrences of a substring replaced by another substring, without altering the original string. Similarly, `strip()` returns a new string with leading and trailing whitespace (or specified characters) removed, leaving the original unchanged. Both methods are non-mutating because strings in Python are immutable.

Exam trap

Python Institute often tests the distinction between methods that return a new string (like `replace()` and `strip()`) versus those that return an index or count (like `index()`, `find()`, and `count()`), trapping candidates who confuse 'returning a value' with 'returning a new string'.

422
Multi-Selectmedium

Which TWO of the following are valid ways to read a file line by line without loading the entire file into memory?

Select 2 answers
A.lines = list(f)
B.for line in f:
C.contents = f.read().split('\n')
D.while True: line = f.readline(); if not line: break
E.lines = f.readlines()
AnswersB, D

Iterates one line at a time.

Why this answer

Option B is correct because iterating directly over a file object with `for line in f:` reads one line at a time from the file's internal buffer, never loading the entire file into memory. This is the idiomatic and memory-efficient way to process large files line by line in Python.

Exam trap

Python Institute often tests the distinction between methods that load the entire file into memory (like `readlines()`, `read().split()`, and `list(f)`) versus the iterator protocol that processes lines lazily, and candidates frequently confuse `list(f)` as being lazy because it uses the file object.

423
MCQmedium

What is the output of the following code? s = 'Hello'; print(s.find('l'))

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

Correct: The first 'l' is at index 2.

Why this answer

The find() method returns the lowest index where the substring 'l' is found. In 'Hello', the first 'l' is at index 2 (0-based).

424
Drag & Dropmedium

Drag and drop the steps to create a Python package with subpackages 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

A package is a directory with __init__.py. Subpackages are subdirectories with their own __init__.py. Modules are placed inside, and imports use dot notation.

425
Multi-Selecteasy

Which TWO of the following file modes will create a new file if it doesn't exist? (Select exactly 2)

Select 2 answers
A.'x'
B.'a'
C.'rb'
D.'w'
E.'r'
AnswersB, D

Creates new file if not exists.

Why this answer

Option B ('a') is correct because the append mode opens a file for writing at the end; if the file does not exist, Python creates it automatically. Option D ('w') is correct because write mode truncates the file if it exists, but also creates a new file if it does not exist.

Exam trap

Python Institute often tests the distinction between 'w' (truncates existing content) and 'a' (preserves existing content) while both create the file if missing, and candidates may incorrectly think 'x' or 'r' also create files.

426
MCQhard

Refer to the exhibit. What is the root cause of the error?

A.The attribute 'age' is not defined in the class or instance.
B.The __init__ method was not called.
C.The attribute 'age' is private.
D.The attribute 'age' is a class attribute but not initialized.
AnswerA

The instance only has 'name', not 'age'.

Why this answer

Option B is correct because the attribute 'age' is not defined anywhere in the class or instance. Option A is incorrect because there is no private attribute involved. Option C is incorrect because __init__ was called.

Option D is incorrect because 'age' is not a class attribute.

427
MCQmedium

You maintain a Python library 'myutils' that is installed as a package in the system. The library has a submodule 'config' that reads configuration from a file. Recently, a user reported that after updating the library, their application still uses the old configuration values. They confirmed that the config file on disk has been updated. The library's __init__.py does: from .config import load_config. The user's application imports load_config from myutils and calls it each time they need configuration. What is the most likely cause of the issue?

A.The user did not restart the Python interpreter, so sys.modules still contains the old module.
B.The import statement in __init__.py is cached, so the module is not reloaded even after update.
C.The library's .pyc files were not regenerated because the .py timestamps were not updated during the install, so Python used the cached bytecode from the previous version.
D.The config module caches the configuration file contents in memory after the first read.
AnswerC

If the .py file's modification time is not newer than the .pyc file, Python uses the bytecode.

Why this answer

Option C is correct because Python caches compiled bytecode in .pyc files. If the .pyc file's timestamp is newer than the corresponding .py file, Python will use the cached bytecode without recompiling. During a package update, if the .py files' timestamps are not updated (e.g., due to a flawed installation process), Python continues to load the old .pyc, causing the old configuration-reading code to execute even though the config file on disk has changed.

Exam trap

Python Institute often tests the misconception that Python always recompiles .pyc files when the source changes, but the trap is that Python relies on file timestamps, not content hashes, so a stale .pyc can persist if the .py timestamp is not updated during installation.

How to eliminate wrong answers

Option A is wrong because the user is calling load_config each time they need configuration, not relying on a module-level cached value; restarting the interpreter would not fix stale bytecode if the .pyc is still newer than the .py. Option B is wrong because the import statement in __init__.py is not cached; Python's import system caches the loaded module object in sys.modules, but the user is importing load_config and calling it repeatedly, so the module is already loaded and the function is executed fresh each call. Option D is wrong because the question states the user confirmed the config file on disk has been updated, and the issue is that the library code itself is stale (not that the config module caches file contents in memory).

428
MCQmedium

A programmer wants to create a class that cannot be instantiated directly, only through a factory method. Which approach should be used?

A.Raise an exception in __init__ if called directly.
B.Define the class as abstract using ABC and @abstractmethod.
C.Override __new__ to raise an exception unless called from a classmethod factory.
D.Use a metaclass to prevent instantiation.
AnswerC

__new__ controls instance creation; raising an exception prevents direct instantiation.

Why this answer

Option C is correct because overriding `__new__` allows the programmer to control instance creation at the lowest level. By checking the call stack or a flag set by a classmethod factory, `__new__` can raise an exception when instantiation is attempted directly, while still allowing the factory method to create instances. This ensures the class cannot be instantiated directly, only through the designated factory.

Exam trap

Python Institute often tests the distinction between `__new__` and `__init__`, and the trap here is that candidates think raising an exception in `__init__` (Option A) is sufficient, not realizing that `__new__` has already created the object and the exception only prevents full initialization, not allocation.

How to eliminate wrong answers

Option A is wrong because raising an exception in `__init__` still allows the object to be partially created (memory allocated by `__new__`), and the exception can be caught, leaving a half-initialized object or causing confusion; it does not prevent instantiation at the allocation stage. Option B is wrong because defining a class as abstract with ABC and @abstractmethod prevents instantiation only if the class has unimplemented abstract methods; if all abstract methods are implemented, the class can be instantiated directly, which does not enforce the factory-only requirement. Option D is wrong because using a metaclass to prevent instantiation is overly complex and not a standard Python pattern for this specific need; it would require overriding `__call__` in the metaclass, which is less direct and more error-prone than overriding `__new__` in the class itself.

429
Multi-Selecthard

Which THREE of the following expressions return the string "Python"? (Choose three.)

Select 3 answers
A."Python"[::2]
B."Python"[:]
C."Python"[0:6:1]
D."Python"[0:6]
E."Python"[:-1]
AnswersB, C, D

Full slice returns the entire string.

Why this answer

Slicing with [0:6], [:], and [0:6:1] all return the entire string 'Python'. [:-1] returns 'Pytho', and [::2] returns 'Pto'.

430
Multi-Selecteasy

Which TWO of the following are immutable in Python?

Select 2 answers
A.Set
B.Tuple
C.String
D.Dictionary
E.List
AnswersB, C

Tuples are immutable.

Why this answer

Tuple (B) is immutable because once created, its elements cannot be added, removed, or changed. This is enforced by Python's internal structure: tuples are stored as a fixed-length array of PyObject pointers, and any attempt to modify them raises a TypeError.

Exam trap

Python Institute often tests the misconception that strings are mutable because they support indexing and slicing, but candidates forget that any operation that appears to change a string actually returns a new string object, leaving the original unchanged.

431
MCQhard

Consider the following code snippet: try: x = int(input()) y = 10 / x print(y) except ZeroDivisionError: print('Division by zero') except ValueError: print('Invalid integer') If the user enters '0', what is the output?

A.No output
B.Both 'Invalid integer' and 'Division by zero'
C.Division by zero
D.Invalid integer
AnswerC

ZeroDivisionError is raised and caught.

Why this answer

When the user enters '0', the input is successfully converted to the integer 0 by int(), so no ValueError occurs. Then 10 / 0 raises a ZeroDivisionError, which is caught by the except ZeroDivisionError block, printing 'Division by zero'. Option C is correct because the code never reaches the ValueError handler.

Exam trap

Python Institute often tests the order of exception handling and the fact that int('0') succeeds, leading candidates to mistakenly think a ValueError occurs or that both exceptions could fire.

How to eliminate wrong answers

Option A is wrong because the ZeroDivisionError is raised and caught, so there is output ('Division by zero'), not no output. Option B is wrong because only one exception occurs (ZeroDivisionError), not both; the ValueError handler is only triggered if int() fails, which it does not here. Option D is wrong because 'Invalid integer' would only print if the input could not be converted to an integer (e.g., entering 'abc'), but '0' is a valid integer string.

432
MCQhard

A developer is implementing a custom context manager to manage database connections. The context manager should automatically roll back the transaction if an exception occurs, but commit if no exception occurs. Which pattern ensures this behavior correctly?

A.def __exit__(self, exc_type, exc_val, exc_tb): self.connection.commit()
B.def __exit__(self, exc_type, exc_val, exc_tb): if exc_type: self.connection.rollback() else: self.connection.commit()
C.def __exit__(self, exc_type, exc_val, exc_tb): self.connection.rollback()
D.def __exit__(self, exc_type, exc_val, exc_tb): if exc_val: self.connection.rollback() else: self.connection.commit()
AnswerB

Checks exc_type; if not None, an exception occurred, so rollback; else commit.

Why this answer

Option B is correct because the `__exit__` method receives the exception type (`exc_type`), value (`exc_val`), and traceback (`exc_tb`) as arguments. By checking `if exc_type:` (which is `None` when no exception occurs, and a class object otherwise), the developer can conditionally roll back the transaction on an exception or commit if the block completes normally. This pattern ensures atomicity and proper resource management for database connections.

Exam trap

Python Institute often tests the distinction between checking `exc_type` vs. `exc_val` vs. `exc_tb`, and candidates mistakenly think any of these three can be used interchangeably, but the canonical and most reliable check is `exc_type` because it is `None` when no exception occurs and a class object otherwise, while `exc_val` could theoretically be `None` even if an exception is raised (though rare).

How to eliminate wrong answers

Option A is wrong because it always calls `commit()`, even when an exception occurs, which would commit partial or erroneous changes and violate transaction atomicity. Option C is wrong because it always calls `rollback()`, discarding successful transactions and causing data loss. Option D is wrong because it checks `exc_val` (the exception instance) instead of `exc_type`; while `exc_val` is also `None` when no exception occurs, the standard and most reliable check is `exc_type` (or `exc_val`), but the option's logic is technically correct in practice, however the question's correct answer explicitly uses `exc_type` as the canonical pattern; more importantly, the option's phrasing 'if exc_val' is less idiomatic and could be considered a trap, but the primary reason it's wrong is that the exam expects the exact pattern shown in B.

433
MCQeasy

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

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

__all__ explicitly lists names to export.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

434
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

435
MCQeasy

A class has a method that does not access any instance or class data. What decorator should be used to define it as a utility method that can be called on the class itself without requiring an instance?

A.@property
B.@staticmethod
C.@abstractmethod
D.@classmethod
AnswerB

Static methods don't take self or cls.

Why this answer

The @staticmethod decorator is used for methods that do not depend on the class or instance state. They can be called on both instances and the class.

436
MCQmedium

A developer wrote a script that processes user input. The script expects a string containing a list of comma-separated values. The user enters "apple, banana, cherry, date". The script uses split() to separate the items. Which code correctly extracts the second item without leading/trailing spaces?

A.items = data.split(); second = items[1]
B.items = data.split(", "); second = items[1]
C.items = data.split(","); second = items[1].strip()
D.items = data.split(","); second = items[2].strip()
AnswerB

Correctly splits on comma-space, directly obtaining the second item without extra spaces.

Why this answer

Option B correctly splits on ', ' which matches the input format, returning the second item without extra spaces. Option A also works but is less direct. Option C splits on whitespace, including commas in items.

Option D gets the third item.

437
MCQeasy

What will be the output of the following code? try: print(1/0) except: print('error') else: print('no error') finally: print('done')

A.no error\ndone
B.error\nno error\ndone
C.done
D.error\ndone
AnswerD

Correct: exception caught, else skipped, finally executed.

Why this answer

Option D is correct because the code raises a ZeroDivisionError when attempting 1/0, which is caught by the bare except clause, printing 'error'. The else clause is skipped because an exception occurred. The finally clause always executes, printing 'done'.

Thus the output is 'error' followed by 'done'.

Exam trap

Python Institute often tests the order of execution in try/except/else/finally, specifically that the else block is skipped when an exception occurs, and that finally always runs, leading candidates to mistakenly include 'no error' or omit 'error'.

How to eliminate wrong answers

Option A is wrong because it suggests the except block was skipped and the else block ran, which would only happen if no exception occurred; but 1/0 raises an exception. Option B is wrong because it includes 'no error' from the else block, which is never executed when an exception is caught. Option C is wrong because it omits 'error', implying the except block did not execute, but the exception is indeed caught and handled.

438
Multi-Selecthard

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

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

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

Why this answer

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

Exam trap

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

439
MCQhard

Refer to the exhibit. What is the output?

A.7
B.10
C.Error
D.14
AnswerB

Correct.

Why this answer

Base.method returns 3*2=6, Derived.method adds 4, so 10.

440
Multi-Selectmedium

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

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

Returns a new string with all lowercase characters.

Why this answer

Option B (str.lower()) is correct because, despite Python strings being immutable, the question asks which methods 'modify the string in place' as a trick. In reality, none of these methods modify the string in place; they all return a new string. However, the PCAP exam sometimes tests whether you know that str.lower() and str.upper() are the only methods among the options that return a new string with the entire string transformed, while the others are often mistakenly thought to modify the original.

The key is that the question's premise is false, and the 'correct' answers are the ones that are most commonly associated with in-place modification in other languages, but in Python they do not.

Exam trap

Python Institute often tests the misconception that string methods like str.replace() or str.strip() modify the string in place, when in fact all string methods return new strings due to immutability, and the question's premise is deliberately misleading to catch candidates who do not understand that no string method modifies in place.

441
MCQeasy

Which of the following is the correct way to open a file for writing in text mode, ensuring that if the file already exists it will be overwritten?

A.open('file.txt', 'x')
B.open('file.txt', 'w')
C.open('file.txt', 'r+')
D.open('file.txt', 'a')
AnswerB

'w' mode overwrites existing content.

Why this answer

Option B is correct because the 'w' mode opens the file for writing in text mode and truncates the file to zero length if it exists, or creates a new file if it does not. This ensures any existing content is overwritten, which matches the requirement.

Exam trap

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

How to eliminate wrong answers

Option A is wrong because 'x' mode opens the file for exclusive creation, raising a FileExistsError if the file already exists, rather than overwriting it. Option C is wrong because 'r+' mode opens the file for both reading and writing without truncating it, so existing content is preserved and not overwritten unless explicitly written over. Option D is wrong because 'a' mode opens the file for appending, writing data at the end of the file without truncating or overwriting existing content.

442
MCQeasy

A developer needs to write binary data to a file. Which file mode should be used to open the file for writing in binary mode without truncating it if it already exists?

A.'wb'
B.'rb'
C.'ab'
D.'wb+'
AnswerC

Opens for appending in binary; does not truncate; writes at end.

Why this answer

Option C ('ab') is correct because the 'a' mode opens the file for appending, which writes data at the end without truncating the existing content, and adding 'b' specifies binary mode. This allows binary data to be written to a file that already exists without losing its current contents.

Exam trap

Python Institute often tests the distinction between 'w' (truncate) and 'a' (append) modes, trapping candidates who assume 'wb' is the only way to write binary data without considering preservation of existing content.

How to eliminate wrong answers

Option A ('wb') is wrong because 'w' mode truncates the file to zero length upon opening, destroying any existing data. Option B ('rb') is wrong because 'r' mode opens the file for reading only, not writing. Option D ('wb+') is wrong because 'w+' mode also truncates the file upon opening, even though it allows both reading and writing.

443
MCQmedium

A developer gets the following error while running a Python script: 'TypeError: not all arguments converted during string formatting'. The relevant code is: print('Progress: %d%%' % (percent)). The variable 'percent' is an integer. What is the most likely cause and fix?

A.There is a mismatch between the number of format specifiers and the number of arguments; add another argument.
B.Convert the integer to a string using str(percent) before formatting.
C.The percent sign must be escaped as '%%' to be treated as a literal.
D.Switch from %-formatting to an f-string: f'Progress: {percent}%'
AnswerC

In %-formatting, a literal percent sign is represented by '%%'.

Why this answer

Option B is correct because the percent sign (%) inside the string is interpreted as a format specifier, not a literal. To insert a literal percent sign, it must be escaped as '%%'. Option A is wrong because the number of arguments matches (one format specifier %d).

Option C is wrong because f-strings, while modern, are not required to fix this particular error. Option D is wrong because int() conversion is unnecessary.

444
MCQhard

Refer to the exhibit. What is the output?

A.3
B.Error
C.A object
D.4
AnswerD

Correct; 1+2+1=4.

Why this answer

The __add__ method adds the two values and adds 1, so 1+2+1=4.

445
MCQmedium

A developer is troubleshooting an ImportError: 'No module named 'config''. The config module is located in a subdirectory 'utils' relative to the script. The script's current working directory is the parent of 'utils'. Which of the following lines, added to the script, will resolve the issue?

A.sys.path.append('utils/config.py')
B.sys.path.append('utils')
C.sys.path = os.path.join(sys.path, 'utils')
D.os.chdir('utils')
AnswerB

This adds the utils directory to the module search path.

Why this answer

The ImportError occurs because Python's module search path (sys.path) does not include the 'utils' subdirectory. Adding 'utils' to sys.path via sys.path.append('utils') tells Python to look inside that directory for modules, resolving the import. Option B is correct because it extends the search path to include the directory containing the config module, without altering the script's working directory or incorrectly appending a file path.

Exam trap

Python Institute often tests the distinction between modifying sys.path with a directory versus a file path, and the trap here is that candidates mistakenly think appending the full file path (option A) or using os.path.join on a list (option C) will work, when only a directory path appended to the list is correct.

How to eliminate wrong answers

Option A is wrong because sys.path expects directory paths, not file paths; appending 'utils/config.py' would cause Python to look for a directory named 'utils/config.py', which does not exist. Option C is wrong because sys.path is a list, not a string, so os.path.join(sys.path, 'utils') will raise a TypeError due to mixing a list with a string. Option D is wrong because os.chdir('utils') changes the current working directory to 'utils', but the script's import statement still looks for 'config' relative to the original working directory; moreover, changing the working directory can break relative file operations elsewhere in the script.

446
Multi-Selecthard

Which THREE are valid escape sequences in Python strings?

Select 3 answers
A.\n
B.\q
C.\\
D.\t
E.\z
AnswersA, C, D

Newline escape sequence.

Why this answer

Option A is correct because \n is a standard escape sequence in Python that represents a newline character (ASCII LF, 0x0A). It is defined in the Python language specification and is commonly used to insert line breaks in string literals.

Exam trap

Python Institute often tests the distinction between valid escape sequences (like \n, \\, \t) and invalid ones (like \q, \z) that beginners might assume exist because they see other backslash combinations in contexts like regex or shell scripting.

447
Multi-Selectmedium

Which TWO statements about method overriding in Python are correct?

Select 2 answers
A.The overriding method can call the parent method using super()
B.The overriding method must have the same name
C.The overriding method requires explicit use of the @override decorator
D.The overriding method must have the exact same parameter list
E.Overriding is resolved at compile time
AnswersA, B

super() allows access to the overridden method.

Why this answer

Option A is correct because the overriding method can call the parent class's version of the method using the built-in `super()` function, which returns a proxy object that delegates method calls to the parent class. This is a fundamental feature of Python's inheritance mechanism, allowing the child method to extend or modify the parent's behavior while still invoking it.

Exam trap

Python Institute often tests the misconception that Python enforces strict method signatures or requires an `@override` decorator, leading candidates to select options D or C, when in fact Python's dynamic nature allows flexible overriding without compile-time checks.

448
Multi-Selectmedium

Which TWO of the following are valid string methods in Python? (Choose two.)

Select 2 answers
A..capitalize()
B..lower()
C..uppercase()
D..titlecase()
E..swapcase()
AnswersA, B

Valid method, capitalizes first character.

Why this answer

A is correct because `.capitalize()` is a built-in string method in Python that returns a copy of the string with its first character capitalized and the rest lowercased. It is part of the standard string methods documented in Python's official library reference.

Exam trap

Python Institute often tests the exact naming of string methods, and the trap here is that candidates may confuse `.uppercase()` or `.titlecase()` with the real methods `.upper()` and `.title()`, or mistakenly think `.swapcase()` is invalid when it is actually a valid method but not one of the two required correct answers.

449
MCQeasy

What is the result of the expression 'Hello'[1:3]?

A.'el'
B.'lo'
C.'He'
D.'ell'
AnswerA

Correct slice from index 1 to 3 exclusive gives 'e' (index1) and 'l' (index2).

Why this answer

In Python, string slicing uses the syntax `string[start:stop]`, where `start` is inclusive and `stop` is exclusive. For `'Hello'[1:3]`, the indices are: index 1 = 'e', index 2 = 'l', and index 3 is not included, so the slice returns 'el'. This is a fundamental string slicing behavior defined in Python's sequence protocol.

Exam trap

Python Institute often tests the off-by-one error in slice stop indices, where candidates mistakenly think the stop index is inclusive and select 'ell' (option D) instead of the correct 'el'.

How to eliminate wrong answers

Option B is wrong because 'lo' would result from slicing `[3:5]` (indices 3 and 4), not `[1:3]`. Option C is wrong because 'He' would result from slicing `[0:2]` (indices 0 and 1), not `[1:3]`. Option D is wrong because 'ell' would result from slicing `[1:4]` (indices 1, 2, and 3), but the stop index 3 excludes index 3, so only two characters are taken.

450
MCQhard

What is the output of the following code? try: raise ValueError('a') except ValueError as e: print(e.args[0]) finally: print('b')

A.a b
B.b a
C.a\nb
D.b
AnswerC

Correct: prints 'a', newline, then 'b'.

Why this answer

Option C is correct because the `finally` block always executes after the `try` block, even when an exception is raised. The `except` block catches the `ValueError` and prints the first argument of the exception (`'a'`), then the `finally` block prints `'b'`. The output is `a` on one line and `b` on the next, matching `a\nb`.

Exam trap

Python Institute often tests the misconception that `finally` runs before `except` or that `print()` outputs on the same line, leading candidates to choose options with incorrect order or missing newlines.

How to eliminate wrong answers

Option A is wrong because it suggests both outputs appear on the same line (`a b`), but `print()` adds a newline by default, so they appear on separate lines. Option B is wrong because it reverses the order to `b a`, but the `finally` block executes after the `except` block, not before. Option D is wrong because it omits the `'a'` output entirely, but the `except` block does execute and prints the exception argument before the `finally` block runs.

Page 5

Page 6 of 7

Page 7

All pages