CCNA Modules and Packages Questions

75 of 112 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

The module's __name__ is the dotted name used in import.

Why this answer

Option C is correct because 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

Absolute import from the shared package.

Why this answer

Option C is correct because 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

Valid import with alias.

Why this answer

Option A is correct because 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
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

Correct. Absolute imports are more explicit and robust.

Why this answer

Option D is correct because 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.

5
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

Correct. Python only searches directories in sys.path for modules.

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.

6
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

Ensures pip installs the latest version of common_lib.

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.

7
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 at startup and its entries are added to sys.path.

Why this answer

Option A is correct because the PYTHONPATH environment variable is a standard mechanism for extending Python's module search path. When Python starts, it reads the PYTHONPATH variable and prepends its contents to sys.path, allowing users to specify additional directories where Python should look for modules before falling back to the default search order.

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.

8
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

This attribute contains the path to the module's file.

Why this answer

Option C is correct because `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.

9
Multi-Selecteasy

Which TWO of the following are valid ways to import a module 'math' in Python?

Select 2 answers
A.import Math
B.import math,
C.from math import *
D.from math import
E.import math
AnswersC, E

Valid wildcard import (though not recommended for large modules).

Why this answer

Options A (import math) and B (from math import *) are valid. Option C has incorrect capitalization (case-sensitive), D is incomplete syntax, and E has a trailing comma which is invalid.

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

Modules are cached in sys.modules. If config.py was imported previously, the cached version is used, and the code is not re-executed.

Why this answer

Option D is correct because 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
Multi-Selectmedium

Which TWO of the following are valid ways to import a function 'foo' from a module 'bar' that is located in a package 'mypackage'?

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

Correct absolute import.

Why this answer

Option B is correct because the syntax `from mypackage.bar import foo` directly imports the function `foo` from the module `bar` within the package `mypackage`. This is the standard Python import statement for importing a specific attribute from a submodule.

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 `from mypackage import bar.foo` is valid because they confuse it with the valid `from mypackage.bar import foo` syntax.

12
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

This adds the directory to the module search path automatically for all Python scripts run in that environment.

Why this answer

Option C is correct. PYTHONPATH is an environment variable that Python checks for additional module search paths. Setting it once system-wide or per user avoids modifying sys.path in each script.

Option A is wrong because relative imports would require restructuring the module into a package, which changes import behavior and may break existing absolute imports. Option B is wrong because __init__.py alone does not make the module discoverable from any path; it still requires the directory to be on sys.path. Option D is wrong because installing a .pth file is system-wide and may not be allowed; also it modifies the search path globally, which is less controlled than PYTHONPATH.

13
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

Relative imports require the module to be part of a package with __package__ set.

Why this answer

Option C is correct because 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.

14
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

__all__ specifies the list of names to be imported when using 'from package import *'.

Why this answer

Option B is correct because the __all__ list controls which names are imported when using 'from package import *'. Option D is correct because the behavior can be customized by defining __all__ in __init__.py. Option A is wrong because submodules are not imported automatically.

Option C is wrong because without __all__, only public names from __init__.py are imported, not submodules. Option E is wrong because 'from package import *' imports names from the package, not the package itself.

15
Multi-Selecteasy

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

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

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

Why this answer

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

Exam trap

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

16
Matchingmedium

Match each code snippet to its output.

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

Concepts
Matches

8

3

1

15

14

Why these pairings

Basic arithmetic operations and operator precedence.

17
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

18
MCQmedium

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

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

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

Why this answer

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

19
Multi-Selecthard

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

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

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

Why this answer

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

Exam trap

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

20
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

21
MCQmedium

What is the most likely cause of this error?

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

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

Why this answer

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

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

22
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

23
Multi-Selecthard

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

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

Appended when site module is processed.

Why this answer

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

Exam trap

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

24
MCQeasy

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

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

The == operator specifies the exact version.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

25
Drag & Dropmedium

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

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

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

26
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

27
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

28
MCQeasy

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

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

Standard best practice to isolate dependencies.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

29
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

30
MCQmedium

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

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

Best practice; ensures version control and isolation.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

31
MCQeasy

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

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

Directly imports the function into the current namespace.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

32
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

33
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

Correct dot notation to import from a submodule.

Why this answer

Option C is correct because 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.

34
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

Correct absolute import.

Why this answer

Option B is correct because 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.

35
MCQhard

A team is developing a large application that consists of multiple components, each housed in separate directories. They want to organize these components under a common namespace package called 'app'. The directory structure is as follows: /opt/project/ ├── components/ │ ├── auth/ (contains __init__.py and modules) │ └── billing/ (contains __init__.py and modules) ├── main.py └── another_location/ └── reports/ (contains __init__.py and modules) The team wants to allow all these components to be imported as subpackages of 'app', e.g., 'import app.auth', 'import app.billing', 'import app.reports'. They have ensured that none of the directories named 'app' exist; instead, they plan to use namespace packages. They create a directory '/opt/project/app/' with an __init__.py file, and move the auth and billing directories under it. However, the reports directory must remain at '/opt/project/another_location/reports/', but they want it to be accessible as 'app.reports'. They attempt to achieve this by adding '/opt/project/another_location/' to the sys.path. When they run main.py, they get an ImportError: No module named 'app.reports'. The auth and billing modules work fine. What is the most likely issue and the correct fix?

A.The sys.path modification is not persistent; they need to set the PYTHONPATH environment variable.
B.The reports package needs to be moved under the app directory physically.
C.The reports directory has an __init__.py file, which conflicts with the namespace package.
D.The app directory has an __init__.py file, which prevents it from being a namespace package. Remove the __init__.py from the app directory.
AnswerD

A namespace package must not have __init__.py; removing it allows the package to be split across multiple directories on sys.path.

Why this answer

Option A is correct because the 'app' directory has an __init__.py file, making it a regular package. Namespace packages must not have __init__.py in the top-level directory to allow extending via sys.path. Removing __init__.py from app/ turns it into a namespace package, allowing reports from another_location to be found.

Option B is incorrect because subpackages can have __init__.py. Option C is incorrect because sys.path modifications are effective for the session. Option D is incorrect because namespace packages are designed to span multiple directories without moving files.

36
MCQmedium

A developer is creating a package that contains a subpackage. The subpackage has an __init__.py file that imports a module named 'helper' from the parent package. Which import statement in the subpackage's __init__.py will correctly import 'helper'?

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

This absolute import explicitly specifies the package hierarchy.

Why this answer

Option A is correct because the subpackage's __init__.py needs to import the 'helper' module from the parent package using an absolute import. The statement 'from mypackage import helper' explicitly references the parent package by its name, which is the standard way to import from a parent package when the package structure is known and avoids ambiguity with relative imports.

Exam trap

Python Institute often tests the confusion between relative import syntax (dots) and absolute imports, tricking candidates into thinking that 'from .. import helper' is the correct way to import from a parent package in a subpackage's __init__.py, when in fact the absolute import is the correct and intended answer for this scenario.

How to eliminate wrong answers

Option B is wrong because 'from . import helper' uses a relative import that refers to the current package (the subpackage itself), not the parent package, so it would look for 'helper' inside the subpackage, not the parent. Option C is wrong because 'from ... import helper' uses three dots, which would go up two levels (grandparent), not one level to the parent, and is incorrect for importing from the immediate parent. Option D is wrong because 'from .. import helper' uses two dots, which in Python relative imports means going up one level from the current package, but this syntax is used within a module inside the subpackage, not in the subpackage's __init__.py itself; in __init__.py, '..' refers to the parent of the subpackage, but the correct relative import would be 'from .. import helper' only if the subpackage is a direct child of the parent, but the question specifies the subpackage's __init__.py, and the absolute import is the safer and intended approach.

37
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

Editable installs use .egg-link or .pth files that can become stale if the source path changes.

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.

38
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

Correct. This command queries PyPI and shows all available versions.

Why this answer

Option A is correct because `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.

39
MCQmedium

Refer to the exhibit. A script executes 'from mypackage import *'. Which functions are available in the global namespace?

A.Only func from module_a
B.It raises an ImportError because __all__ should contain function names
C.None, because __all__ lists modules, not functions
D.func from both module_a and module_b
AnswerC

Correct. __all__ defines what names are imported; here it imports the modules, so functions remain in the module namespace.

Why this answer

Option C is correct because when `from mypackage import *` is executed, Python looks for the `__all__` list in the package's `__init__.py` file. In this exhibit, `__all__` is defined as `['module_a', 'module_b']`, which are module names, not function names. The `import *` statement imports the modules listed in `__all__` into the global namespace, not their individual functions.

Therefore, `func` from either module is not directly available; you would need to reference them as `module_a.func` or `module_b.func`.

Exam trap

The trap here is that candidates often assume `__all__` must contain function or variable names, but it can also list submodule names, and `import *` only imports those listed names—not their nested contents—into the global namespace.

How to eliminate wrong answers

Option A is wrong because `func` from `module_a` is not directly imported into the global namespace; only the module `module_a` itself is imported. Option B is wrong because `__all__` can contain module names or attribute names; it does not raise an `ImportError` when it contains module names—it simply imports those modules. Option D is wrong because `func` from both modules is not directly available; only the modules `module_a` and `module_b` are imported into the global namespace.

40
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

Packages can be nested.

Why this answer

Option A is correct because 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.

41
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

Correct. This imports specific names from the module.

Why this answer

Option B is correct because 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.

42
MCQmedium

A developer is troubleshooting a Python application that fails to import a custom module named 'utils'. The file 'utils.py' exists in the same directory as the main script. Which of the following is the most likely cause of the import failure?

A.There is a circular import between utils.py and the main script.
B.The directory containing utils.py is not in sys.path.
C.The directory lacks an __init__.py file.
D.The utils.py file contains a syntax error.
AnswerB

Python searches for modules in directories listed in sys.path. If the script's directory is not included, the import will fail unless the script is run from that directory.

Why this answer

When Python imports a module, it searches for it in the directories listed in sys.path. Even if 'utils.py' is in the same directory as the main script, that directory may not be automatically included in sys.path if the script is not run as a module (e.g., using python main.py from a different working directory). The most common cause of such a failure is that the script's directory is missing from sys.path, which prevents Python from locating the file.

Exam trap

Python Institute often tests the misconception that files in the same directory are always importable, but the trap is that Python's import search path depends on how the script is executed, not just file location.

How to eliminate wrong answers

Option A is wrong because a circular import would cause an ImportError only if the modules depend on each other at the top level, but the question states the file exists and the failure is on import, not a runtime error; circular imports typically raise an ImportError with a specific message, not a simple failure to find the module. Option C is wrong because __init__.py is required only for directories to be treated as packages (for implicit namespace packages in Python 3.3+ it is optional), and the question involves a single module file, not a package directory. Option D is wrong because a syntax error in utils.py would cause an ImportError only when the module is actually loaded and executed, not a failure to find the module; the error would be a SyntaxError, not a missing module error.

43
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

pip configuration allows specifying extra index URLs for package resolution.

Why this answer

Option C is correct because 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.

44
MCQeasy

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

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

This is the standard Python idiom for executable scripts.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

45
MCQhard

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

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

This defines the public API of the package.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

46
MCQhard

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

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

This function is designed for programmatic module loading.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

47
Matchingmedium

Match each Python built-in function to its description.

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

Concepts
Matches

Returns the length of an object

Generates a sequence of numbers

Returns a sorted list from an iterable

Returns index and value pairs

Aggregates elements from multiple iterables

Why these pairings

These are common built-in functions in Python.

48
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

49
MCQmedium

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

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

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

Why this answer

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

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

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

50
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

51
MCQeasy

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

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

The standard for packaging.

Why this answer

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

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

52
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

53
Multi-Selecthard

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

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

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

Why this answer

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

Exam trap

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

54
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

55
Multi-Selectmedium

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

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

Python creates __pycache__ on first import.

Why this answer

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

Exam trap

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

56
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

57
MCQeasy

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

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

This imports only the specified function.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

58
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

59
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

60
MCQeasy

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

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

The error clearly states the module is not found.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

61
Multi-Selectmedium

Which TWO statements about namespace packages are true?

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

Correct. PEP 420 introduced namespace packages in Python 3.3.

Why this answer

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

Exam trap

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

62
MCQeasy

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

63
MCQmedium

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

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

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

Why this answer

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

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

Exam trap

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

How to eliminate wrong answers

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

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

64
MCQhard

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

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

This is the standard Python idiom for controlled public API.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

65
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

66
MCQeasy

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

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

Correctly adds the directory to the module search path.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

67
MCQmedium

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

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

Version 2.0 is available and satisfies the requirement.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

68
MCQmedium

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

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

Makes numpy accessible as analytics.np and imported once.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

69
Drag & Dropmedium

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

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order

Why this order

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

70
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

71
Multi-Selecteasy

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

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

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

Why this answer

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

Exam trap

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

72
Multi-Selectmedium

Which TWO statements about the sys module are true?

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

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

Why this answer

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

Exam trap

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

73
MCQmedium

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

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

Common issue when multiple Python versions or virtual environments exist.

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

74
MCQhard

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

75
MCQmedium

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

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

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

Why this answer

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

Exam trap

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

How to eliminate wrong answers

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

Page 1 of 2 · 112 questions totalNext →

Ready to test yourself?

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