Courseiva

CCNA Modules and Packages Questions

75 of 85 questions · Page 1/2 · Modules and Packages · Answers revealed

1
MCQhard

A developer runs the following code in a script that is not part of a package: import sys sys.path.insert(0, '/custom/path') import mymodule print(mymodule.__name__) What is the output if 'mymodule' is found at '/custom/path/mymodule.py'?

A.mymodule.py
B.__main__
C.mymodule
D./custom/path/mymodule.py
AnswerC

This is the correct answer because, for an imported module, `__name__` is set to the module's dotted import name—exactly the identifier used in the `import` statement, with no trailing `.py`. For a file `mymodule.py` imported as `import mymodule`, Python sets `mymodule.__name__` to `'mymodule'`, allowing the module to know its own name within the system. If the module is part of a package, the value would include the package path, such as `'package.mymodule'`, but the base case is simply the module name.

Why this answer

When a module is imported, Python assigns the `__name__` attribute to the module's name as a string (e.g., 'mymodule'), not the filename with extension. Since the script is not part of a package and the module is found at a custom path, `mymodule.__name__` is simply 'mymodule'.

Exam trap

Python Institute often tests the distinction between `__name__` and the file path or extension, hoping candidates confuse the module's name with its filename or full path.

How to eliminate wrong answers

Option A is wrong because `__name__` does not include the '.py' extension; it is the module's bare name. Option B is wrong because `__name__` is only set to `__main__` when the module itself is executed as the top-level script, not when it is imported. Option D is wrong because `__name__` is not the full file path; the path is used for locating the module but is not stored in `__name__`.

2
MCQeasy

A developer wants to use a function 'calculate' from a module 'math_ops' that is located in a sibling directory '../shared/' relative to the current script. What is the correct way to import it using an absolute import assuming the shared directory is a package with __init__.py and the project root is in sys.path?

A.from .shared.math_ops import calculate
B.from ..shared.math_ops import calculate
C.from shared.math_ops import calculate
D.import ..shared.math_ops
AnswerC

This is an absolute import: Python searches for the shared package by scanning the directories listed in sys.path, which normally includes the directory containing the script, the standard library, and site-packages. If shared is a top-level package in that path (e.g., a folder with an __init__.py in the project root or a namespace package), the import will succeed. This is the correct and recommended way to import from a top-level package because it is unambiguous and matches the developer's intent. The from ... import statement also directly binds the calculate function into the current namespace, making the call site simple and explicit.

Why this answer

Absolute imports in Python use the project root as the base, not relative paths. Since the project root is in sys.path, 'from shared.math_ops import calculate' directly references the 'shared' package at the top level, regardless of the current script's location. This is the standard absolute import syntax as defined in PEP 328.

Exam trap

Python Institute often tests the distinction between absolute and relative imports, and the trap here is that candidates confuse the dot notation for relative imports with absolute imports, or assume that '..' is valid syntax for absolute imports when it is not.

How to eliminate wrong answers

Option A is wrong because it uses a relative import with a single dot ('.shared'), which implies the current package, but 'shared' is a sibling directory, not a subpackage of the current script's package. Option B is wrong because it uses a relative import with two dots ('..shared'), which would go up one level from the current package, but this is a relative import, not an absolute import as required by the question. Option D is wrong because 'import ..shared.math_ops' is invalid syntax; relative imports require the 'from' keyword and cannot be used with the 'import' statement directly.

3
Multi-Selecteasy

Which TWO of the following are valid ways to import a function named 'func' from a module 'mymod' that is in the same directory as the script?

Select 2 answers
A.from mymod import func as myfunc
B.import mymod.func
C.import func from mymod
D.from mymod import func
E.from .mymod import func
AnswersA, D

This is a valid import statement aliasing the function `func` from module `mymod` to the local name `myfunc`. Python's `from module import name as alias` syntax allows you to reference the function under a different identifier, which can prevent name collisions and improve readability. It correctly imports the function object.

Why this answer

The syntax `from mymod import func as myfunc` is a valid Python import statement that imports the function `func` from the module `mymod` and binds it to the local name `myfunc`. Since `mymod` is in the same directory as the script, Python's module search path includes that directory, so the import succeeds without needing a relative import prefix.

Exam trap

Python Institute often tests the distinction between absolute and relative imports, and the trap here is that candidates mistakenly think a dot prefix (`.mymod`) is always valid for importing from the same directory, but relative imports only work inside a package, not for standalone scripts.

4
MCQeasy

A script contains the following lines: import math from math import sqrt print(math.sqrt(16)) print(sqrt(25)) What is the output when the script is executed?

A.4.0 and 5.0
B.An error occurs because sqrt is imported twice, causing a name clash.
C.4 and 5
D.4.0 and an error, because sqrt is not defined after importing math.
AnswerA

The script imports the math module and also imports the sqrt function directly into the global namespace. The first print uses math.sqrt(16), which returns 4.0. The second print uses the directly imported sqrt(25), which returns 5.0. Both calls are valid, and the output is 4.0 followed by 5.0 on separate lines. There is no conflict because the names math and sqrt refer to different objects.

Why this answer

The script imports the math module and also imports the sqrt function directly. Both math.sqrt and sqrt are available. Calling math.sqrt(16) returns 4.0, and calling sqrt(25) returns 5.0.

The output is two lines: 4.0 and 5.0. The other options misstate the return type, claim an error due to double import, or incorrectly assume sqrt becomes undefined.

Exam trap

The trap here is thinking that importing a module and a function from that module causes a conflict or that sqrt returns an integer.

5
MCQmedium

A team is developing a large application and wants to organize code into packages. Which of the following is a best practice for package design?

A.Use relative imports inside the package to avoid hardcoding the package name
B.Keep all modules in a single package for simplicity
C.Avoid using __init__.py to keep packages lightweight
D.Use absolute imports with the package name to prevent breakage when the package is moved
AnswerD

Absolute imports that start with the full top-level package name (for example `from myapp.utils.helpers import parse`) make the dependency graph explicit and easy to reason about, even when a submodule is moved within the package. Because every import references the same root, the interpreter can detect a broken path immediately and give a clear `ModuleNotFoundError` instead of silently resolving to a different local module. This clarity reduces the risk of accidental name shadowing and aligns with PEP 8's recommendation that absolute imports are the more robust, readable choice for production code. Anchoring imports to the package name ensures that refactoring tools and static analyzers can follow the actual location of each name.

Why this answer

Using absolute imports with the full package name (e.g., `from package.module import something`) ensures that the import path is explicit and independent of the module's location within the package. This prevents breakage when the package is moved or installed in a different location, as the import references the top-level package name rather than a relative path that may change. Absolute imports are the recommended style in PEP 8 for clarity and maintainability in larger applications.

Exam trap

Python Institute often tests the misconception that relative imports are always safer because they avoid hardcoding the package name, but the trap is that relative imports break when the package is moved or when modules are executed as scripts, whereas absolute imports with the package name remain stable.

How to eliminate wrong answers

Option A is wrong because relative imports (e.g., `from . import module`) can become fragile when the package structure is reorganized or when the module is executed as a script, leading to `ImportError` due to the implicit relative path. Option B is wrong because keeping all modules in a single package violates the principle of separation of concerns and makes the codebase harder to navigate, test, and reuse; packages should be organized into sub-packages based on functionality. Option C is wrong because `__init__.py` is required (in Python 3.3+ for regular packages, though namespace packages can omit it) to mark a directory as a Python package; omitting it can cause import failures unless using implicit namespace packages, which is not a best practice for a large application.

6
MCQmedium

A Python script fails with 'ModuleNotFoundError: No module named 'myapp.config''. The environment variable PYTHONPATH is not set. Which of the following is the most likely cause?

A.The module is located in a directory not included in sys.path
B.The module's __init__.py is missing
C.The module is installed in a different Python version's site-packages
D.The module has a syntax error
AnswerA

The import system resolves module names by scanning every directory listed in sys.path, which normally includes the script's own directory, entries from PYTHONPATH, and the interpreter's site-packages. If the module's parent directory is not represented anywhere in that list, Python cannot locate the file regardless of how clearly the module is named, and the import statement terminates with ModuleNotFoundError. This is the most direct and common cause of this exception, and the fix is to add the directory to sys.path, modify PYTHONPATH, or install the module properly.

Why this answer

When PYTHONPATH is not set, Python relies solely on sys.path to locate modules. sys.path includes the script's directory, standard library paths, and site-packages. If 'myapp.config' is not in any of these directories, Python raises ModuleNotFoundError. Option A correctly identifies that the module is in a directory not included in sys.path.

Exam trap

Python Institute often tests the distinction between a module not being found (ModuleNotFoundError) versus a package structure issue (missing __init__.py) or a code error (SyntaxError), tempting candidates to pick the more specific but incorrect cause.

How to eliminate wrong answers

Option B is wrong because a missing __init__.py prevents a directory from being recognized as a package, but the error 'No module named 'myapp.config'' indicates the entire module is not found, not that it fails to import from within a package. Option C is wrong because if the module were installed in a different Python version's site-packages, the error would still be ModuleNotFoundError, but the most likely cause given PYTHONPATH is unset is that the module's directory is simply not in sys.path, not a version mismatch. Option D is wrong because a syntax error in the module would cause a SyntaxError when Python tries to execute the module, not a ModuleNotFoundError.

7
MCQhard

You are a DevOps engineer managing a Python application that consists of multiple microservices. One microservice, 'data_processor', imports a shared library 'common_lib' which is also used by other microservices. The shared library is developed in a separate repository and is installed via pip in each microservice's virtual environment as an editable package (pip install -e). Recently, you updated 'common_lib' with new functions, but when you redeploy 'data_processor' (by restarting the container), the new functions are not available; the old version is still used. The container uses a Docker image built from a requirements file that specifies 'common_lib' from a Git repository. You verify that the Git commit hash in the requirements file points to the latest version. What is the most likely cause and what is the correct course of action?

A.Add the common_lib source directory to sys.path in the microservice code.
B.Rename the package in the requirements file to force a fresh install.
C.Update the commit hash or use a version tag that points to the latest, and rebuild the Docker image without using cache (--no-cache).
D.Change the Python interpreter to a different version.
AnswerC

Updating the commit hash or version tag in the dependency specification to point to the latest release, then rebuilding the Docker image with --no-cache, directly forces pip to fetch the newer revision instead of reusing cached layers. The --no-cache flag prevents Docker from reusing the old RUN pip install layer, ensuring the build environment is fresh and that the upgraded common_lib is actually installed into the image.

Why this answer

When a Docker image is built, pip installs the package from the Git repository at the commit hash specified in the requirements file. Even if the requirements file points to the latest commit, Docker's layer caching may reuse a previously built layer that contains the old version of the package. Rebuilding the image with --no-cache forces Docker to re-execute the pip install step, fetching the latest code from Git and installing the updated common_lib.

Simply restarting the container does not rebuild the image, so the old installed package persists.

Exam trap

Python Institute often tests the misconception that restarting a container or redeploying without rebuilding the image will pick up changes from a Git-based pip dependency, when in fact the package is frozen in the image layer until the image is rebuilt with a fresh pip install.

How to eliminate wrong answers

Option A is wrong because adding the common_lib source directory to sys.path would only affect runtime module resolution if the source were present in the container, but the issue is that the installed package itself is outdated; sys.path manipulation does not update the installed package. Option B is wrong because renaming the package in the requirements file would create a different package name, breaking imports and requiring code changes; it does not address the caching problem. Option D is wrong because changing the Python interpreter version does not affect which version of common_lib is installed; the package version is determined by the Git commit hash and the pip install step, not the Python version.

8
Multi-Selecthard

Which THREE of the following statements about Python's module search path are true?

Select 3 answers
A.The PYTHONPATH environment variable can be used to add custom directories to sys.path.
B.The site-packages directory is searched before the PYTHONPATH directories.
C.The directory containing the script being run is added to sys.path automatically.
D.The current working directory is always the last entry in sys.path.
E.The sys.path can be modified at runtime to change the module search path.
AnswersA, C, E

PYTHONPATH is read by Python at start-up and its entries are prepended to sys.path, so custom directories become importable without editing code. This directly satisfies the stem's requirement that the variable can extend the module search path.

Why this answer

Option A is correct because PYTHONPATH is an environment variable whose directories are prepended to the default module search path, effectively extending sys.path so custom modules can be imported. Option C is correct because when a script is executed, Python automatically inserts the directory containing that script at the front of sys.path, allowing sibling modules to be imported. Option E is correct because sys.path is an ordinary Python list that can be modified at runtime (e.g., via sys.path.append() or sys.path.insert()) to alter where subsequent imports are resolved.

Option B is wrong because PYTHONPATH directories are searched before site-packages, not after. Option D is wrong because the current working directory is not always the last entry in sys.path; its presence and position depend on how Python is invoked (for example, it appears first when running interactively or with -c/-m, and is not added at all when running a script).

Exam trap

Python Institute often tests the exact order of module search path components, and the trap here is that candidates mistakenly believe site-packages is searched before PYTHONPATH, or that the current working directory is always last, when in fact the script's directory is first and PYTHONPATH precedes site-packages.

9
MCQhard

A developer notices that a custom package 'mypackage' is not being found when importing, even though it is installed in the site-packages directory. The developer suspects a conflict with another package of the same name. Which command should the developer run to diagnose the location from which Python is importing the package?

A.print(mypackage)
B.print(__file__)
C.print(mypackage.__file__)
D.import os; print(os.getcwd())
AnswerC

For an imported module, the `__file__` attribute stores the filesystem path of the source file from which the module was loaded. When `mypackage` is a package, its `__file__` points to the package's `__init__.py` file, which is exactly the location of the package on disk in most ordinary cases. This is the standard, programmatic way to determine where a package or module resides, making this option correct.

Why this answer

`mypackage.__file__` returns the filesystem path from which the module was loaded, allowing the developer to see exactly which `mypackage` Python is using. This directly reveals if the wrong package (e.g., from a different location or a conflicting installation) is being imported instead of the intended one.

Exam trap

The trap here is that candidates often confuse `__file__` (which gives the current script's path) with `module.__file__` (which gives the imported module's path), or they assume `print(mypackage)` will show the path directly, when in fact it may only show a module representation without the full path in all contexts.

How to eliminate wrong answers

Option A is wrong because `print(mypackage)` will print a string representation of the module object (e.g., `<module 'mypackage' from '/path/to/...'>`), but it does not reliably show the file path in all Python versions or environments, and it is not the standard diagnostic command. Option B is wrong because `print(__file__)` prints the path of the current script, not the imported package, so it provides no information about where `mypackage` is located. Option D is wrong because `print(os.getcwd())` prints the current working directory, which is unrelated to the import resolution path for installed packages.

10
MCQmedium

A developer has a module 'config.py' with the following content: # config.py import os DATABASE_URL = os.getenv('DATABASE_URL', 'localhost') Another module 'app.py' imports config and uses DATABASE_URL. During testing, the environment variable is set correctly, but the import still uses the default value 'localhost'. What is the most likely reason?

A.The import statement in app.py is placed inside a function, so it is not executed.
B.The module was imported using 'from config import DATABASE_URL' which creates a separate copy.
C.The environment variable is only read when the function is called, not at import time.
D.Python caches modules; config.py was imported earlier without the environment variable, and the cached version is reused.
AnswerD

Python records every imported module in sys.modules, and a later import of the same module simply fetches that cached object instead of re-executing the file. If config.py was imported earlier in the same interpreter session before the environment variable was set, its module-level code—including the os.getenv call—has already run and stored a stale default. All subsequent imports, whether 'import config' or 'from config import DATABASE_URL', see that cached module and its fixed value, so the code is not re-executed.

Why this answer

Python caches imported modules in `sys.modules`. If `config.py` was imported earlier in the test session (e.g., during test discovery or another import) before the environment variable `DATABASE_URL` was set, the cached module would retain the default value `'localhost'`. Subsequent imports, even after setting the environment variable, reuse the cached module, so `os.getenv('DATABASE_URL', 'localhost')` is not re-evaluated.

Exam trap

Python Institute often tests the misconception that `from module import name` creates an independent copy, when in fact it only binds a reference to the same object, and the real issue is Python's module caching and the timing of environment variable reads.

How to eliminate wrong answers

Option A is wrong because placing an import inside a function does not prevent its execution; the import is executed when the function is called, and the module is still cached. Option B is wrong because `from config import DATABASE_URL` creates a local name binding to the same object, not a separate copy; the issue is about the value at import time, not copying. Option C is wrong because `os.getenv` is called at import time (when the module is first loaded), not when a function is called; the environment variable is read once during module initialization.

11
MCQhard

You are a developer for a data science team. The team uses a shared module 'utilities' located at /team/shared/utilities.py. This module is not part of any package, and they want to import it from various project scripts without copying the file. Some projects are in /home/user/proj_A/ and others in /var/data/proj_B/. Currently, each script manually adds /team/shared/ to sys.path using sys.path.insert(0, '/team/shared/'). This works but is repetitive. The team wants a cleaner solution that also works when the script is run from different working directories. They consider creating a package 'utilities' by adding an __init__.py to the directory and using relative imports. However, the module currently uses absolute imports for some external libraries. What is the best course of action to allow clean imports of utilities from any location while minimizing changes to the module itself?

A.Create an empty __init__.py in /team/shared/ to make it a namespace package.
B.Set the PYTHONPATH environment variable to include /team/shared/ in the shell profile.
C.Place a .pth file in the site-packages directory that points to /team/shared/.
D.Convert utilities.py into a package by adding __init__.py and using relative imports inside.
AnswerB

Setting PYTHONPATH in the shell profile prepends /team/shared/ to the module search path (sys.path) for every Python process spawned from that shell. This allows `import utilities` to resolve cleanly without altering the module's internals, placing the shared directory in a well-known environment variable rather than hard-coding it into each script. It is minimal, reversible, and does not touch the Python installation or require packaging changes.

Why this answer

Setting the PYTHONPATH environment variable to include /team/shared/ is the best solution because it automatically adds that directory to the module search path for all Python scripts without modifying the module itself or requiring repetitive code. This approach works regardless of the current working directory and preserves the module's existing absolute imports. Other options either do not add the directory to the search path, require modifying the module, or are more complex to implement.

Exam trap

A common mistake is to think that adding an __init__.py file makes a directory importable from anywhere. In reality, __init__.py only marks a directory as a Python package, but the directory must already be in the module search path (sys.path) to be imported. Without PYTHONPATH or sys.path manipulation, the package is not discoverable from arbitrary locations.

How to eliminate wrong answers

Option A is wrong because creating an empty __init__.py in /team/shared/ would make it a regular package, not a namespace package, and would not automatically add the directory to the module search path; scripts would still need to modify sys.path or rely on PYTHONPATH. Option C is wrong because placing a .pth file in site-packages adds the directory to sys.path only for the specific Python installation where site-packages resides, which may not be portable across different environments or projects, and it requires administrator privileges. Option D is wrong because converting utilities.py into a package by adding __init__.py and using relative imports would require rewriting the module to use relative imports, which contradicts the goal of minimizing changes and could break existing absolute imports for external libraries.

12
MCQhard

A Python project has the following directory structure: project/ __init__.py main.py subpackage/ __init__.py module.py Inside 'module.py', there is a function 'func' that needs to be imported in 'main.py'. The team wants to import 'func' using a relative import from 'main.py'. However, when they run 'python main.py' from the project root, they get an ImportError. What is the most likely reason?

A.The 'project' directory does not contain an __init__.py file.
B.The function 'func' is not defined as a public function.
C.Relative imports cannot be used in scripts executed directly as __main__.
D.The module name 'module.py' contains a hyphen.
AnswerC

When a file is run directly as a script, e.g., `python project/module.py`, Python sets `__name__` to `'__main__'` and leaves `__package__` empty or `None`. A relative import such as `from .module import func` relies on `__package__` to determine the package the module belongs to; without that context, Python raises `ImportError: attempted relative import with no known parent package`. This is the exact error described in the question. Relative imports only work when the module is imported as part of a package, for example when the project is run with `python -m project.module` from the parent directory.

Why this answer

When a Python script is executed directly (e.g., `python main.py`), its `__name__` is set to `"__main__"`, not the package name. Relative imports (e.g., `from .subpackage.module import func`) rely on the `__package__` attribute being set to the package hierarchy, which only happens when the module is imported as part of a package. Since `main.py` is run as the top-level script, it has no package context, causing an `ImportError`.

Exam trap

Python Institute often tests the distinction between running a script directly (`python main.py`) versus running it as a module (`python -m package.main`), and candidates mistakenly think that adding `__init__.py` files or using absolute imports will fix the relative import error.

How to eliminate wrong answers

Option A is wrong because the `project` directory does contain an `__init__.py` file (as shown in the directory structure), so the package is properly initialized. Option B is wrong because Python does not enforce 'public' functions for imports; any name defined in a module can be imported unless it is prefixed with an underscore (e.g., `_func`), and the question does not indicate such a naming convention. Option D is wrong because the module name is `module.py`, which contains no hyphens; hyphens are not allowed in Python module names anyway, as they would cause a syntax error during import.

13
Multi-Selecteasy

Which TWO statements about the 'from package import *' statement are correct?

Select 2 answers
A.It imports the package itself as a module.
B.Without __all__, it imports all public names from the package's __init__.py and all submodules.
C.It imports all submodules of the package by default.
D.If __all__ is defined in __init__.py, only the names in __all__ are imported.
E.The behavior can be customized by defining the __all__ list in __init__.py.
AnswersD, E

When `__all__` is defined in the package's `__init__.py`, `from package import *` imports exactly the names contained in that list. Any name not present in `__all__` is ignored, even if it is a public variable, function, or a submodule also defined in the package. This explicit list overrides the default underscore-filtering behavior and gives the package author precise control over the subset of the package's API that is exposed to star imports.

Why this answer

When `__all__` is defined in a package's `__init__.py`, the `from package import *` statement imports only the names listed in that `__all__` list. This is the explicit mechanism Python provides to control the public API of a package when using the wildcard import syntax.

Exam trap

The PCAP exam often tests the misconception that `from package import *` automatically imports all submodules, when in fact it only imports names from the package's `__init__.py` (or those listed in `__all__`), and submodules must be explicitly imported or listed to be included.

14
Matchingmedium

Match each code snippet to its output.

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

Concepts
Matches

8

3

1

15

14

Why these pairings

Understand operator precedence: exponentiation > multiplication/division > addition/subtraction. Parentheses override precedence. Integer division (//) returns floor division quotient, while modulo (%) returns remainder.

15
Multi-Selecthard

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

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

A C extension is a binary shared library (e.g., .so or .pyd) that Python loads through the dynamic linker. If a required dependency is missing, a symbol is unresolved, or the binary ABI is incompatible, the OS raises a low-level loader error which Python catches and re-raises as ImportError. The file may exist and be syntactically valid, but the extension's initialization cannot complete, making this a legitimate import-time failure mode.

Why this answer

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

Exam trap

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

16
MCQhard

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

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

insert(0, '/home/user/custom') places the custom directory at the very beginning of sys.path, making it the first location searched by the import machinery. This guarantees that modules in that directory take precedence over identically named modules found later in the path, including the standard library and site-packages. It also avoids issues with the working directory or other early entries, which is why insert(0, ...) is the conventional idiom for local module overrides.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

17
MCQmedium

What is the most likely cause of this error?

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

This is exactly what produces the traceback. When __init__.py runs, it imports submodule.py; submodule.py then executes 'from . import __init__', which returns the partially initialized package module already sitting in sys.modules. Because the package's attribute (e.g., a class or function) has not yet been defined, Python raises ImportError: cannot import name that from a partially initialized module. The cycle is between the package initializer and one of its own submodules.

Why this answer

A circular import occurs when `__init__.py` and `submodule.py` attempt to import each other (directly or indirectly) before either module is fully initialized. In Python, when a module is being imported, it is added to `sys.modules` as a partially initialized module; if another module tries to import it during that time, it may receive an incomplete or empty module object, leading to an `ImportError` or `AttributeError`. This is a common cause of import failures in packages where initialization logic in `__init__.py` depends on submodules that themselves import from the package root.

Exam trap

The PCAP exam often tests the misconception that import errors are caused by missing `__all__` or incorrect execution directory, when the actual root cause is a circular dependency between `__init__.py` and a submodule that creates a partially initialized module state.

How to eliminate wrong answers

Option A is wrong because a missing `__all__` definition does not cause an import error; `__all__` only controls what is exported with `from package import *`, not the ability to import individual submodules. Option B is wrong because executing `main.py` from outside the package directory does not inherently cause import errors if the package is installed or the Python path is set correctly; the error described is more specific to import mechanics. Option C is wrong because `submodule.py` cannot import a module named `__init__` as a separate file; `__init__.py` is a special file that initializes a package, not a module that can be imported by name.

Option D is wrong because invalid relative import syntax (e.g., `from . import submodule` with a missing dot or incorrect parent) would raise a `SyntaxError` or `ImportError` with a clear message about attempted relative import beyond top-level package, not the generic error implied here.

18
MCQeasy

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

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

This command correctly uses the pip package manager with an explicit version specifier. The == operator, an exact version pin defined by PEP 440, tells pip to install precisely requests 2.25.1 from PyPI, bypassing any newer or older release. This ensures reproducible dependency behavior across different machines and deployment stages.

Why this answer

Both options B and C are correct because they use the standard pip syntax for pinning a specific version: `package==version`. The command `pip install requests==2.25.1` (B) works on systems where `pip` is linked to Python 3, while `pip3 install requests==2.25.1` (C) explicitly invokes the Python 3 version of pip. Both achieve the same result—installing requests exactly version 2.25.1.

Option A fails to specify a version, and option D contains a typo ('instll') that will fail.

Exam trap

A common pitfall is assuming that `pip3` is incorrect or non-standard. In reality, both `pip` and `pip3` are valid commands for Python 3 environments; the key is the version-pinning syntax (`==`). The question tests whether the candidate recognizes the correct syntax for specifying an exact version, not the distinction between `pip` and `pip3`.

How to eliminate wrong answers

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

19
Drag & Dropmedium

Drag and drop the steps to create and activate a virtual environment in Python into the correct order.

Drag or tap steps into the slots.

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

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

20
MCQmedium

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

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

This is the correct way to reload a module in Python 3. It takes a module object (already imported) and re-executes its source code, updating the module's attributes in place. It is particularly useful during development to pick up changes without restarting the interpreter. Note that it returns the updated module object, and other references to the old module still point to the same object (since it mutates in place).

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

21
MCQeasy

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

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

Using 'python -m venv' creates an isolated environment with its own Python binary and site-packages directory, allowing each project to install exactly the dependencies and versions it needs without interfering with other projects. This is the standard, built-in best practice for managing project dependencies in a shared Python environment, and it also makes it easy to generate a reproducible requirements.txt for teammates.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

22
MCQmedium

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

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

`from .stats import normalize` is a relative import: the leading dot tells CPython's import machinery to start from the current package, `analytics`, and resolve `.stats` as `analytics.stats` (PEP 328). This works regardless of the absolute `sys.path` layout, whether `analytics` is installed as a package or invoked from a script, and it avoids name collisions with any unrelated top-level `stats` module. Since the statement appears in `analytics/__init__.py`, `.stats` is unambiguous and correctly loads the sibling submodule, making `normalize` available as `analytics.normalize`.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

23
MCQmedium

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

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

Packaging the library as a proper Python package and installing it with pip into each project's virtual environment is the industry-standard way to share internal code. The package gets its own version number and can be pinned to a tag or commit in git (for instance, pip install "mylib @ git+https://repo.git@v1.2.3"), with pip resolving its dependencies and installing it into an isolated, per-project site-packages area. This gives you reproducible builds, clean uninstall/upgrade paths, and consistent import behavior across every project.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

24
MCQeasy

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

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

This statement directly locates the `reverse` function inside the `utilities.strings` submodule and binds it under the name `reverse` in the current namespace. Unlike the other options, no package or submodule qualifier is needed; you can invoke `reverse()` immediately. It is the only option that gives you the function itself rather than a module or package reference.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

25
MCQeasy

A developer creates a package named 'mypkg' with an __init__.py file. Inside the package, there is a module 'utils.py'. Which of the following is the correct way to import the function 'helper' from 'utils' from outside the package?

A.import mypkg.utils.helper
B.import mypkg; mypkg.utils.helper
C.from mypkg.utils import helper
D.from mypkg import utils.helper
AnswerC

This is the correct and idiomatic form because it explicitly names the submodule `utils` and the object `helper` in the `from ... import ...` syntax. The statement `from mypkg.utils import helper` tells Python to load `mypkg/utils` (the submodule) and then extract the attribute `helper` from that module's namespace, binding it locally as `helper`. This is the standard approach for importing a function or variable from a submodule directly, avoiding the need for dotted attribute chains.

Why this answer

It uses the standard Python syntax for importing a specific name from a submodule within a package: `from package.module import name`. This directly imports the `helper` function into the current namespace, making it callable without any prefix. The `__init__.py` file marks `mypkg` as a package, and `utils.py` is a module inside it, so `from mypkg.utils import helper` is the proper way to access `helper` from outside the package.

Exam trap

Python Institute often tests the distinction between importing a module versus importing an attribute from a module, and the trap here is that candidates confuse the `import` statement (which only accepts modules/packages) with the `from ... import` statement (which can import any object), leading them to choose Option A or D.

How to eliminate wrong answers

Option A is wrong because `import mypkg.utils.helper` attempts to import a module named `helper`, but `helper` is a function, not a module; Python's import system only supports importing modules or packages, not individual objects like functions or classes, via the `import` statement. Option B is wrong because `mypkg.utils.helper` is not a valid attribute access after `import mypkg`; `import mypkg` only imports the top-level package, and to access `utils` you would need to import `mypkg.utils` explicitly (e.g., `import mypkg.utils`), otherwise `mypkg.utils` is undefined. Option D is wrong because `from mypkg import utils.helper` uses dot notation in the import name, which is invalid syntax; the `from ... import` statement expects a single module or a comma-separated list of names, not a dotted path to an attribute.

26
Multi-Selectmedium

Which TWO methods are valid ways to import a function named 'foo' from a module 'bar' that is part of a package 'pkg'?

Select 2 answers
A.import bar
B.from pkg.bar import foo
C.import pkg; pkg.bar.foo
D.from pkg import bar; bar.foo
E.import pkg.bar.foo
AnswersB, D

This is the canonical absolute import: the full module path `pkg.bar` is resolved, the submodule is loaded, and the name `foo` (the function object) is bound directly into the current namespace. After execution, you can call `foo()` without any package or module qualifier. It is explicit, unambiguous, and does not depend on any earlier side-effect imports.

Why this answer

The 'from pkg.bar import foo' syntax directly imports the 'foo' function from the 'bar' submodule within the 'pkg' package, making 'foo' available in the current namespace. Option D is also correct because it first imports the 'bar' module from 'pkg' using 'from pkg import bar', then accesses 'foo' as an attribute of 'bar' (bar.foo), which is a valid two-step approach.

Exam trap

Python Institute often tests the distinction between importing a module versus importing an attribute from a module, and the trap here is that candidates mistakenly think 'import pkg.bar.foo' (Option E) is valid syntax, when in fact you can only import modules or packages with the dotted-path import statement, not functions or classes.

27
MCQmedium

Your company has two separate Python packages: 'app' and 'lib'. They are maintained by different teams. 'app' depends on 'lib', but 'lib' is still under development and its API changes frequently. To avoid breaking 'app', the team decides to use a virtual environment and install a specific version of 'lib'. However, during development, they need to test 'app' with the latest 'lib' changes from the Git repository. The current workflow is: (1) activate virtual env, (2) install 'lib' from local source using `pip install -e /path/to/lib`. This installs 'lib' as a development package. But one developer reports that after pulling latest 'lib' changes, importing 'lib' in 'app' still uses the old version even after re-running pip install -e. What is the most likely reason?

A.Python caches imported modules in sys.modules, so importing again does not reload the module from disk.
B.The package 'lib' is being imported as a namespace package, so changes are not picked up.
C.The .pyc files are not being invalidated because the timestamps are not updated.
D.The editable install may still point to an old copy of the library if the source directory was moved or if there is a stray .egg-link file.
AnswerD

An editable install for 'lib' registers the source directory via a .pth file or an .egg-link file, which adds that directory to sys.path. If the source directory was moved after the editable install, the recorded path becomes stale; alternatively, a leftover .egg-link from an earlier install can point to the old location. Re-running pip install -e should update this, but if it happened before the move or was interrupted, the import mechanism will still reference the old copy, so changes in the current directory are ignored.

Why this answer

The most likely reason is D. When using `pip install -e` (editable install), pip creates a special `.egg-link` file (or similar pointer) in the site-packages directory that points to the source directory. If the source directory was moved, renamed, or if a stale `.egg-link` file remains from a previous install, pip may still reference the old location, causing the old version to be imported even after re-running the install command.

This is a known subtlety of editable installs, especially when the source code is managed under version control and the directory structure changes.

Exam trap

Python Institute often tests the subtle difference between a stale import cache (sys.modules) and a stale install pointer (editable install link), leading candidates to incorrectly choose the caching option when the real issue is a broken or outdated path reference in the development install.

How to eliminate wrong answers

Option A is wrong because Python's `sys.modules` cache only affects modules already imported in the current interpreter session; re-running `pip install -e` and then starting a fresh Python process would not be affected by this cache. Option B is wrong because namespace packages are a different concept (PEP 420) and do not relate to the failure to pick up changes after an editable install; the issue is about the install pointer, not the package type. Option C is wrong because `.pyc` file invalidation is based on source file timestamps or hash comparison, and `pip install -e` does not modify `.pyc` files; the problem is that the import system is loading from a different location entirely, not that bytecode is stale.

28
MCQmedium

Refer to the exhibit. A developer runs 'pip install pandas==2.0.0' but gets an error stating that the required version is not available. Which command should be used to list all available versions of pandas?

A.pip index versions pandas
B.pip search pandas
C.pip show pandas
D.pip list --all pandas
AnswerA

pip index versions pandas is correct because it contacts the configured package index (PyPI by default) and fetches the release history for the pandas project, listing every available version in ascending order. This is the only option that actually asks the remote index about versions, and it is the pip-native way to check which releases exist before installing or pinning one. Note that this subcommand is experimental, but it is still the right choice among the four.

Why this answer

`pip index versions pandas` is the command that queries the Python Package Index (PyPI) for all available versions of the specified package. This command was introduced in pip 21.1 and is the proper way to list version history without attempting to install.

Exam trap

Python Institute often tests the distinction between commands that query the remote index (`pip index`) versus commands that inspect the local environment (`pip show`, `pip list`), and candidates frequently confuse `pip search` (which searches package names) with listing versions.

How to eliminate wrong answers

Option B is wrong because `pip search pandas` is a deprecated command that searches for packages by name or description in PyPI, not for listing available versions of a specific package; it was removed in pip 23.0 due to XMLRPC API issues. Option C is wrong because `pip show pandas` displays metadata for an already installed package (version, location, dependencies), not available versions from the remote index. Option D is wrong because `pip list --all pandas` is not a valid pip syntax; `pip list` lists installed packages, and `--all` shows outdated packages, but it cannot filter by a specific package name in that way.

29
Multi-Selectmedium

Which TWO of the following statements about Python packages are true?

Select 2 answers
A.A package can contain subpackages.
B.An __init__.py file can be empty.
C.Packages cannot be imported using the import statement with dot notation.
D.An __init__.py file is required in every directory to make it a package.
E.A package is a single .py file.
AnswersA, B

A package can contain subpackages. This is correct because packages are essentially directories that map to importable namespaces, and those directories can contain other package directories. When a package directory contains an `__init__.py` (or qualifies as a namespace package), its subdirectories with `__init__.py` become subpackages, allowing hierarchical imports such as `import parent.child.module`. This nesting is fundamental to organizing large projects into logical, reusable components without forcing every module to live at the top level.

Why this answer

Python packages are directories that can contain subpackages (nested directories with their own __init__.py files), forming a hierarchical namespace. This allows for organized module grouping, such as `package.subpackage.module`, which is a core feature of Python's module system.

Exam trap

Python Institute often tests the misconception that an __init__.py file is always required for a directory to be a package, but since Python 3.3, namespace packages without __init__.py are valid, making option D a classic trap.

30
Multi-Selecteasy

Which TWO of the following are valid ways to import specific names from a module?

Select 2 answers
A.from module import * (only names listed in __all__)
B.from module import name1, name2
C.from module import name as alias
D.import name1, name2 from module
E.import module.name1
AnswersB, C

This is the canonical Python syntax for importing one or more specific names directly into the current namespace. When you write `from module import name1, name2`, Python loads the entire module, but only the named attributes become local bindings—`name1` and `name2` are immediately accessible without any module prefix. This form gives you precise control over which objects you bring into scope, avoiding all extraneous names and clearly documenting the dependencies of your code.

Why this answer

The `from module import name1, name2` syntax allows importing specific names from a module directly into the current namespace. Option C is also correct because `from module import name as alias` provides the same functionality while allowing you to rename the imported name to avoid naming conflicts.

Exam trap

Python Institute often tests the distinction between `import module.name` (which is invalid for importing a specific name) and `from module import name` (which is correct), leading candidates to mistakenly think dot notation can import individual attributes.

31
MCQmedium

A developer is working on a project that requires the use of a third-party package hosted on a private repository. The developer wants to ensure that the package can be imported without specifying the full repository URL each time. Which approach should be taken?

A.Append the repository path to sys.path in the script.
B.Place the package files in the site-packages directory manually.
C.Configure the repository URL in pip's configuration file or in requirements.txt.
D.Use os.system to run a pip install command from within the script.
AnswerC

This is the standard, reproducible way to make Python's packaging tooling use a private or alternate repository: specify an index URL via index-url or extra-index-url in pip.conf, or use a fully-qualified requirement line (e.g., --extra-index-url) in requirements.txt. During installation, pip queries the configured indexes, resolves the complete dependency graph, and installs the package plus all of its dependencies into site-packages as wheel or sdist distributions. This method respects version constraints, generates proper distribution metadata, and works consistently across environments because the configuration is declarative and versionable.

Why this answer

Configuring the repository URL in pip's configuration file (e.g., `pip.conf`, `pip.ini`, or `~/.config/pip/pip.conf`) or in `requirements.txt` using the `--index-url` or `--extra-index-url` option allows pip to resolve the package from the private repository automatically. This approach ensures that the package can be installed and imported without manually specifying the full URL each time, as pip will use the configured index to locate and download the package.

Exam trap

Python Institute often tests the distinction between runtime import path manipulation (like `sys.path`) and package installation configuration, trapping candidates who confuse adding a directory to `sys.path` with configuring a remote package index for pip.

How to eliminate wrong answers

Option A is wrong because appending the repository path to `sys.path` only adds a directory to Python's module search path, which is used for importing already-installed modules; it does not install the package from a remote repository or resolve dependencies. Option B is wrong because manually placing package files in `site-packages` bypasses pip's dependency resolution, version management, and integrity checks, leading to potential conflicts or incomplete installations. Option D is wrong because using `os.system` to run a pip install command from within the script is a fragile, non-portable approach that mixes installation logic with runtime code, and it does not provide a persistent configuration for future imports.

32
MCQeasy

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

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

This is the canonical Python idiom for conditional execution. The interpreter assigns the special variable __name__ the value '__main__' only when the source file is run directly as the main program (e.g., `python my_module.py`). When the file is imported as a module, __name__ becomes the module's fully qualified name, so the equality check fails and run() is not invoked, allowing safe import without side effects.

Why this answer

Both options A and B are correct because they are identical and represent the standard Python idiom `if __name__ == '__main__': run()`. When the script is run directly, Python sets `__name__` to `'__main__'`, triggering the function. When imported, `__name__` is the module name, so the function is not executed.

Options C and D are incorrect: C relies on an environment variable that is not standard, and D checks `sys.argv[0]` which is the script path, not the module name.

Exam trap

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

How to eliminate wrong answers

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

33
MCQhard

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

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

importlib.import_module(mod_name) is the correct way to dynamically load a module when its name is only known at runtime, because it accepts a string and returns the corresponding module object while registering it in sys.modules. It uses the standard import machinery, supports both absolute and relative imports (with a package argument), and is designed exactly for this programmatic use case. This makes it the appropriate replacement for older, deprecated functions like load_module.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

34
Matchingmedium

Match each Python built-in function to its description.

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

Concepts
Matches

Returns the length of an object

Generates a sequence of numbers

Returns a sorted list from an iterable

Returns index and value pairs

Aggregates elements from multiple iterables

Why these pairings

The correct matches are: len() returns length, map() applies a function, filter() filters by truth, zip() combines iterables. Common confusions involve swapping the definitions of map and len, or filter and zip.

35
MCQhard

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

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

This is the correct explanation. Python searches the directories and zip files listed in sys.path in order, and for a dotted import like 'common.helpers', it looks for a package (a directory with __init__.py) named 'common' in each path entry. If an earlier sys.path entry contains a different 'common' package that lacks a 'helpers' submodule, Python imports that shadowing package and then attempts to find 'helpers' within it, raising ModuleNotFoundError before ever reaching the intended /opt/app/common/ package. This is a classic path-shadowing bug that causes the real file to be completely ignored.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

36
MCQmedium

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

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

For a directory to be a regular package, Python requires a valid `__init__.py`; when that file is missing, Python 3.3+ treats the directory as a namespace package. A namespace package executes no initialization code, so the `from mypackage.func1 import func1` lines that would normally populate the package namespace never run. The package is still importable, but it appears empty — exactly matching the failure to find `func1` while `import mypackage` succeeds.

Why this answer

If the `mypackage` directory is found but its `__init__.py` is missing, invalid, or not executed (e.g., due to being a namespace package in Python 3.3+), the `from mypackage import *` statement will not trigger the imports defined in `__init__.py`. Consequently, `func1` and `func2` are never bound in the package namespace, leading to a `NameError` when the script tries to call `func1()`. This scenario occurs when the package is located via `sys.path` but the `__init__.py` is not properly processed, often because the directory is treated as a namespace package (PEP 420) rather than a regular package.

Exam trap

The PCAP exam often tests the distinction between regular packages (with `__init__.py`) and namespace packages (without `__init__.py` in Python 3.3+), trapping candidates who assume that a directory containing a package structure always executes its `__init__.py` regardless of file presence or validity.

How to eliminate wrong answers

Option A is wrong because the problem states that the import works (i.e., the package is found), so the current working directory must be in `sys.path` or the package is accessible via another path entry; the error occurs after import, not during it. Option B is wrong because `__all__` explicitly includes `'func1'` and `'func2'`, so it does not hide them; in fact, `__all__` controls what `from mypackage import *` exports, and here it correctly lists both functions. Option D is wrong because the imports in `__init__.py` use absolute imports (`from mypackage.module1 import func1`), which are not relative and do not depend on the current working directory; relative imports would use a leading dot (e.g., `from .module1 import func1`).

37
MCQeasy

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

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

setup.py is the standard configuration and build script for Python packages, used by setuptools (or distutils) to define all distribution metadata—such as the package name, version, description, authors, and, crucially, dependencies via the `install_requires` keyword. When a developer runs commands like `python setup.py sdist` or `bdist_wheel`, this file is the source of truth for what goes into the package and what dependencies it declares, making it the correct place to specify the dependency on the other custom module.

Why this answer

setup.py is the standard file used to specify metadata and dependencies for a Python package. It contains information such as the package name, version, author, and a list of required packages (install_requires). It is used by setuptools to build and distribute the package.

Exam trap

PCAP often tests the confusion between setup.py and requirements.txt, where candidates might think requirements.txt is used for package metadata, but it is only for dependency listing.

How to eliminate wrong answers

Option B is wrong because MANIFEST.in is used to specify additional files to include in the source distribution, such as data files, but it does not specify dependencies or metadata. Option C is wrong because __init__.py is used to mark a directory as a Python package, but it does not contain package metadata or dependency information. Option D is wrong because requirements.txt is used to list dependencies for a specific environment, but it is not used for packaging metadata; it is typically for development or deployment, not for distribution.

38
MCQmedium

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

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

This option incorrectly treats current directory, PYTHONPATH, and site-packages as three distinct search locations, whereas all are simply elements of the single sys.path list. The current directory (specifically the script's directory) is placed at sys.path[0], and PYTHONPATH directories are added immediately after it, while site-packages appears later, but the interpreter never performs separate 'phases' for these; it linearly walks the combined sys.path list. Moreover, the phrase 'current directory' is imprecise because Python uses the script's directory for file execution, not the process's current working directory.

Why this answer

When Python imports a module, it first searches the directory containing the input script (or current working directory), then iterates through the directories listed in the PYTHONPATH environment variable, and finally checks installation-dependent default paths such as site-packages. This order is reflected in sys.path, which is built from the script directory, PYTHONPATH entries, and default site-packages. Option B accurately lists this sequence: current directory, then PYTHONPATH, then site-packages.

Exam trap

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

How to eliminate wrong answers

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

39
Multi-Selecthard

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

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

This is true: the import system walks through the directories and zip archives listed in `sys.path` sequentially, and the first entry that contains the requested module (or package) is used; Python does not continue searching later entries for an alternative. This is why the order of `sys.path` is critical—adding a directory to the front can shadow a standard-library module or another installed package. If no matching module is found, an `ImportError` is raised after the entire list has been exhausted.

Why this answer

Python's import mechanism iterates through `sys.path` in order and stops at the first directory containing the requested module. Option E is correct: the directory containing the script (or the current directory when running interactively) is inserted at the beginning of `sys.path` at startup. Options A, C, and D are false: the current working directory is not always first (the script's directory takes precedence), `sys.path` is initialized from the `PYTHONPATH` environment variable *in addition to* default paths, and `sys.path` is a list, not a tuple.

Therefore, only two statements are true.

Exam trap

The Python Institute often tests that `sys.path` is a list, not a tuple, and that the script's directory, not the current working directory, is inserted first. Candidates may mistakenly think `PYTHONPATH` is the sole source of `sys.path` initialization, but it is only one of several sources.

40
MCQhard

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

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

When importing `mypackage.subpackage1`, Python executes the `__init__.py` of each package along the dotted path to initialize them as proper packages. This happens because the import system processes each component sequentially: first `mypackage` is imported, which runs its `__init__.py`, then its submodule `subpackage1` is imported, which runs its own `__init__.py`. This two-step initialization is fundamental to Python's package system, ensuring parent packages are fully loaded before their subpackages.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

41
Multi-Selectmedium

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

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

On the first import of a module, Python's import system compares the source file's timestamp or hash against any existing cached bytecode; if no matching `.pyc` exists, it compiles the module and writes the resulting bytecode into the `__pycache__` directory. This occurs transparently as part of the import machinery, with no explicit user action, and it does not apply to the top-level script executed with `python script.py`—only to modules that are imported.

Why this answer

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

Exam trap

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

42
MCQeasy

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

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

`import math as m` is the correct and idiomatic way to import the `math` module while binding it to the local name `m`. The `as` clause in an import statement creates an alias for the module object, so every subsequent reference to `m` (such as `m.sqrt(2)`) accesses the `math` module's functionality without needing to type the full module name. This is a standard feature of the import system, commonly used to shorten long module names or avoid name conflicts.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

43
MCQeasy

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

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

This is the correct and idiomatic way to import exactly one function from a module. It binds the name `calculate` directly in the current namespace, so you can call `calculate(...)` without a module prefix, and it avoids pulling in the entire `formulas` module as a separate local name. This form also makes the dependency explicit, which improves readability and reduces the risk of accidentally shadowing other names.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

44
MCQeasy

A user runs script.py and gets the above error: ModuleNotFoundError: No module named 'mypackage'. Which of the following is the most likely cause?

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

ModuleNotFoundError: No module named 'mypackage' means the import system searched all entries in sys.path and found no module or package named 'mypackage'. This happens when the package is not installed (e.g., not in site-packages), the current working directory is not on sys.path, or the package's parent directory is not listed in the Python path. The fix is to install the package or adjust PYTHONPATH/sys.path so that the import machinery can locate it.

Why this answer

The error message 'ModuleNotFoundError: No module named 'mypackage'' indicates that Python cannot find the module 'mypackage'. This typically occurs when the package is not installed or not present in sys.path. Option C directly addresses this cause.

The other options are less plausible: Option A would raise an AttributeError, not a ModuleNotFoundError; Option B might cause import issues but would likely result in a circular import error or import error due to naming conflicts; Option D's syntax error would prevent the script from running at all. Therefore, Option C is the most probable cause.

Exam trap

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

How to eliminate wrong answers

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

45
Multi-Selectmedium

Which TWO statements about namespace packages are true?

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

Namespace packages were introduced in Python 3.3 via PEP 420, which rewrote the import machinery to allow packages to exist without an __init__.py file. Before that release, every package had to contain __init__.py, and a directory without it was not importable as a package. Therefore, the namespace package concept is supported only in Python 3.3 and later.

Why this answer

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

Exam trap

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

46
MCQhard

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

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

The leading dot indicates a relative import from the current package (`pack`). This statement imports the `mod` submodule from the `subpack` subpackage that is a child of the current package. This is the standard way to import a module from a sibling subpackage in a package, ensuring the import is resolved relative to the current package's location, not the top-level `sys.path`.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

47
MCQeasy

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

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

This is the correct approach. The sys.path attribute is a list of directory strings that Python searches in order when resolving imports. list.append() is the standard method for adding a single element to the end of the list, so /home/user/mylibs becomes available for subsequent import statements, though only for the current process.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

48
MCQmedium

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

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

Use pip install package==2.0 because the error message explicitly lists 2.0 as the only available version; requesting that exact version aligns the requirement with what the index can supply. '==' is an exact version pin, so pip will select that version without ambiguity. This resolves the immediate failure, and if an older pin is needed, the dependency requirement must be updated rather than the environment.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

49
MCQmedium

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

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

Adding 'import numpy as np' in every module that uses numpy is the standard explicit approach, but it only populates that module's local namespace with np. It does not define numpy as a package attribute such as analytics.np, and it does not establish a single import point that all package code can rely on. If the version or alias ever changes, every module must be edited individually, which defeats the goal of a shared common import.

Why this answer

To use numpy in regression.py, that module must have its own import statement, e.g., 'import numpy as np'. Python caches modules in sys.modules, so loading happens only once regardless of where the import statement appears. Thus, repeating 'import numpy as np' in each module that needs it is both correct and efficient, and it respects namespace isolation.

Exam trap

The trap is the misconception that package-level __init__.py imports are necessary to avoid multiple imports or to share names across modules. In reality, Python's caching prevents redundant execution, and name visibility is not automatic.

How to eliminate wrong answers

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

50
Drag & Dropmedium

Drag and drop the steps to perform unit testing with the unittest framework in Python into the correct order.

Drag or tap steps into the slots.

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

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

51
MCQhard

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

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

When a module is first imported, Python stores the resulting module object in `sys.modules` under its full qualified name; every later `import` statement checks `sys.modules` first and returns that same object without re-reading the source file. In an egg-link development environment, the source directory is the one being imported, so you are editing the exact file that was loaded — but the interpreter has already cached the compiled, executed version of that module. You must use `importlib.reload(module)` or restart the process to force reparsing and re-execution of the modified `.py` file.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

52
Multi-Selecteasy

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

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

When a module is executed directly as a script, Python assigns the literal string '__main__' to its __name__ attribute, whereas an imported module receives its normal dotted name. Comparing __name__ to '__main__' thus allows you to detect whether the current file is the entry point of the program. This pattern is the standard way to protect executable code so it runs only when the file is launched directly, not when it is imported by another module.

Why this answer

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

Exam trap

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

53
Multi-Selectmedium

Which TWO statements about the sys module are true?

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

Calling sys.exit() stops a Python program by raising the SystemExit exception, and when no status argument is supplied the exit code is 0, meaning successful termination. The absence of an argument is equivalent to passing None, which the interpreter treats as 0 for the process exit status. Because SystemExit is an exception, code in finally blocks still runs, and an outer try/except can intercept it, so sys.exit() is not an abrupt low-level kill.

Why this answer

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

Exam trap

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

54
MCQmedium

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

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

Pip installs packages into the site-packages directory of the specific Python interpreter that invoked it, e.g., when using `python -m pip` versus a different interpreter. If the script runs under another interpreter—such as a different virtual environment, a system Python, or an IDE's bundled runtime—that interpreter's `sys.path` won't include the package's location, producing an ImportError. This is the classic environment-mismatch cause.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

55
MCQhard

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

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

This is correct because the --user flag makes pip install the package into the current user's private site-packages directory (e.g., ~/.local/lib/python3.x/site-packages), which is owned by that user and therefore requires no elevated permissions. It resolves the permission error without altering system Python packages, and the directory is automatically included in sys.path by default. This is a safe, supported way to install packages when you lack administrative rights, though virtual environments are often preferred for isolation.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

56
MCQmedium

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

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

The AttributeError occurs because `__init__.py` only imports the `calc` module itself (e.g., via `from . import calc`), so the package namespace of `tools` contains the name `calc`, but not `add`. In Python, the attributes of a package are exactly the names bound in its `__init__.py`; importing a submodule does not automatically copy that submodule's functions into the package's top level. Thus `tools.add` is an undefined attribute, while `tools.calc.add` works.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

57
Drag & Dropmedium

Drag and drop the steps to create a simple HTTP server using the http.server module in Python into the correct order.

Drag or tap steps into the slots.

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

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

58
MCQmedium

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

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

When mypackage is a single-file module, it contains no namespace for submodules, so `from mypackage import mymodule` treats mymodule as an attribute that must exist in that file. Since no such attribute is defined, the import machinery raises `ImportError: cannot import name 'mymodule' from 'mypackage'` with the file location of the module. This is the most likely cause because the traceback location is the mypackage module itself, not a package directory, and it aligns with how Python distinguishes modules from packages.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

59
MCQmedium

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

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

Correct. The leading `..` is a relative import that ascends one level from the current subpackage `data.io` to the parent package `data`, then enters the sibling `utils` subpackage/module, from which `helper` is imported. This is the proper PEP 328 syntax for referring to a sibling in a package hierarchy, and it works regardless of the top-level package's absolute location on `sys.path`.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

60
MCQmedium

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

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

The leading double dot in from ..utils import helpers marks this as a relative import that climbs one level above the current package. If this line appears in main.py at the project root, main.py is being executed as the __main__ module rather than as an importable package member, so its __package__ is empty and there is no parent package to resolve the dots. This raises ImportError: attempted relative import with no known parent package, which is exactly why this is the only statement that fails and the correct answer.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

61
MCQmedium

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

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

Importing `validate_transaction` directly from its defining submodule and binding it in `finance/__init__.py` creates a single, callable attribute `finance.validate_transaction`. This is the recommended re-export pattern for exposing a clean public API: users get a flat namespace while the implementation remains organized under submodules. The function's original module is unchanged, but the package-level binding gives the desired shortcut.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

62
MCQeasy

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

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

This is the canonical package layout: each directory—`analytics`, `statistics`, and `ml`—contains an `__init__.py` file, which marks it as a regular Python package. The `__init__.py` files are executed when the package is imported, and their presence allows the import system to traverse the hierarchy (e.g., `import analytics.ml`). This structure works in both Python 2 and Python 3 and is the required format for a standard (non-namespace) package.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

63
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 Python executes a script from standard input (for example, via `python < script.py`), there is no script directory to place at the front of `sys.path`. In that situation, CPython sets `sys.path[0]` to the empty string `''`, which the import system interprets as "search the current working directory." Because `print(sys.path[0])` prints that empty string, the output is a blank line, and the value itself is the documented signal that the script came from stdin. This is a deliberate design decision so that modules in the current directory remain importable even when no script file path exists.

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.

64
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

Recording exact installed versions with `pip freeze` captures the precise dependency state, and `pip install -r requirements.txt` reproduces those pinned versions elsewhere. This satisfies the requirement for identical module versions across environments, since unpinned installs would resolve to newer releases.

Why this answer

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

65
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 the desired functions directly into `__init__.py` with relative imports, e.g. `from .submodule import func1`, binds those names in the package's namespace at import time. This is the canonical re-export pattern: after this line, `import package; package.func1` and `from package import func1` both succeed, while the submodule remains accessible as `package.submodule`. It gives the package a stable public API without duplicating logic.

Why this answer

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

66
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

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.

67
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

The correct diagnosis: Python's json.load() is a strict parser that follows RFC 8259, and a trailing comma after the last element is not valid JSON syntax. The file likely contains something like [{"a":1},{"b":2},], which causes the parser to encounter a comma before the closing bracket and raise JSONDecodeError with a message such as 'Expecting value'. No amount of variable handling or file mode changes can repair that malformed structure.

Why this answer

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.

68
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

When Python imports a package, the path-based finder scans sys.path from index 0 upward and uses the first directory that contains a matching __init__.py file. That directory is bound to the package name, and the search stops immediately, so later directories are never examined. This deterministic first-match resolution ensures predictable behavior even when multiple copies of the same package exist on the path.

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.

69
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

The variable 'settings' in the script and 'config.settings' point to the same dictionary instance in memory. In Python, assignment and import bind names to objects rather than copying the object's data. Since the dictionary is mutable, performing an in-place operation such as settings['new_key'] = value updates the single shared dictionary; no extra mechanism is needed for the change to be visible through config.settings.

Why this answer

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

70
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

Placing __all__ = ['mod1', 'mod2'] in the package's __init__.py is the canonical way to declare the package's public interface. When from utils import * is executed, the __init__.py code runs first, and the import system reads the __all__ list from the package's namespace, importing only the listed submodules. This also aids static analysis tools and IDE autocomplete by making the intended exports explicit, and prevents unintended names from leaking out in wildcard imports.

Why this answer

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.

71
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

Inside a package, sub2 is a sibling of sub1, so a bare import searches the top-level namespace and fails. Python 3 requires an explicit relative import, from .sub2 import helper, to resolve the sibling subpackage within mypackage.

Why this answer

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.

72
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

PEP 420 introduced implicit namespace packages, which allow a dotted package name to be composed from multiple separate directories on sys.path without requiring __init__.py in any of them. When the import system encounters a directory named home that has no __init__.py, it records that directory as one portion of the package and continues scanning later sys.path entries for additional home directories, assigning the combined list of portions to __path__. This is exactly the mechanism that lets two physically separate directory trees collectively provide the submodules of the package home.

Why this answer

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.

73
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

Python's import machinery validates cached bytecode by comparing the source file's modification time (and often size) with the values stored in the .pyc header. If an installer copies only the .py files without updating their mtimes—for example, by preserving timestamps from the build or using a tool that does not touch the destination files—the old .pyc still appears to match the unchanged source timestamp. Python then loads the stale bytecode instead of recompiling, so even though the .py file on disk contains the new code, the interpreter executes the previous version.

Why this answer

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

74
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

Setting __all__ = ['Circle', 'Square'] at the top level of shapes.py explicitly whitelists those two classes for wildcard imports; any other public name, such as Triangle, will be ignored by from shapes import *. This is the canonical Python mechanism for declaring a module's public API, and it is also honored by documentation generators and linters, making the module's intended exports unambiguous.

Why this answer

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.

75
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 is the correct fix because sys.path is a list of directories Python searches when resolving import statements. Appending 'utils' adds that directory to the end of the list, making any Python module or package inside it visible to the import system. Since the target module lives directly in utils, adding this directory allows 'import config' or a similarly named module to be found.

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.

Page 1 of 2 · 85 questions totalNext →

Ready to test yourself?

Try a timed practice session using only Modules and Packages questions.