Which of the following best describes a module in Python?
A module in Python is simply a single .py file that contains Python code. This code may include functions, variables, classes, or even executable statements.
Key points to remember:
A module is always a single file, not a folder.
You can import a module using import module_name.
Modules help organize code and make it reusable across multiple programs.
Example of a Python module:
# file: greetings.py
def hello():
return "Hello!"
Then it can be imported in another file:
import greetings
print(greetings.hello())
Tip: Use modules to break large programs into smaller, manageable parts.
Which import statement correctly imports the math module in Python?
In Python, the correct and standard way to load a built-in or user-defined module is by using the import statement.
import math loads the entire math module.
After importing, you can access its functions like math.sqrt() or math.pi.
Other keywords like include, using, or require do not exist in Python’s import system.
Example usage:
import math
result = math.sqrt(25)
print(result) # 5.0
Tip: When in doubt, remember that Python uses the import keyword for all module-loading operations.
You want to import only the sqrt function from the math module. Which statement should you use?
Python allows you to import specific functions from a module using the from module import name syntax. This makes it easy to use the imported function directly without prefixing it with the module name.
In this case, importing sqrt from the math module looks like this:
from math import sqrt
print(sqrt(16)) # 4.0
import sqrt from math is not valid Python syntax.
using and include are not Python import keywords.
Tip: Use this import style when you only need a few specific functions from a large module.
What is the primary purpose of a __init__.py file inside a folder?
The __init__.py file is used to tell Python that a folder should be treated as a package. This allows you to import modules from that folder using standard import statements.
Without an __init__.py file, older versions of Python would not recognize the folder as a package.
In modern Python versions, it's still commonly used for organizing package behavior.
You can also add initialization code inside __init__.py if needed.
Example structure:
my_package/
__init__.py
utils.py
Then you can import like this:
from my_package import utils
Tip: Even when optional, including __init__.py helps keep your package structure clear and predictable.
Which of the following statements is true about built-in Python modules?
Python comes with many built-in modules that are ready to use without any additional installation. Examples include:
math – for mathematical functions
os – for interacting with the operating system
sys – for system-specific parameters and functions
random – for generating random numbers
Key points:
You do not need to install these modules using pip.
They can be imported in your scripts using import module_name.
Built-in modules are maintained as part of Python’s standard library and are compatible with Python 3.
Tip: Familiarize yourself with Python’s standard library. It can save time by providing pre-built functions for common tasks.
You have created a custom module calculator.py with the following content:
# calculator.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Which of the following statements correctly imports and uses the add function in another Python file?
When using custom modules, Python allows multiple ways to import and use functions:
Option 1:import calculator imports the entire module. You access functions with the module prefix: calculator.add().
Option 2:from calculator import add imports only the add function. You can call it directly as add() without prefixing.
Option 3:import add from calculator is invalid Python syntax.
Example using Option 1:
import calculator
print(calculator.add(5, 3)) # 8
Example using Option 2:
from calculator import add
print(add(5, 3)) # 8
Tip: Use from module import function if you only need specific functions, and import module if you plan to use multiple functions to avoid polluting the namespace.
You want to import the random module but refer to it with a shorter name rnd in your code. Which statement achieves this?
Python allows you to assign an alias to a module using the as keyword. This is useful for shortening module names or avoiding conflicts.
Option 1: Correctly imports the random module as rnd, allowing usage like rnd.randint().
Option 2: Invalid syntax. You cannot alias a function directly with from module import alias in this way.
Option 3: Correct syntax but not the option we chose; it works but the alias is different.
Option 4:using is not a Python keyword.
Example:
import random as rnd
number = rnd.randint(1, 100)
print(number) # Outputs a random number between 1 and 100
Tip: Use aliases for long module names or to avoid conflicts, especially with modules from external libraries.
Which of the following statements correctly imports multiple functions sin and cos from the math module?
Python allows importing multiple functions from a module using from module import func1, func2. You can also alias them using as.
Option 1: Correctly imports sin and cos and uses them directly.
Option 2: Invalid syntax. You cannot import functions this way with dot notation.
Option 3: Correct syntax using aliases s and c for the functions.
Option 4: Correct because both Option 1 and Option 3 work properly.
Example using Option 1:
from math import sin, cos
print(sin(0)) # 0.0
print(cos(0)) # 1.0
Example using Option 3:
from math import sin as s, cos as c
print(s(0)) # 0.0
print(c(0)) # 1.0
Tip: Use aliases if function names conflict with your own variables or if you want shorter names for readability.
Which of the following correctly distinguishes a module from a package in Python?
Understanding the difference between modules and packages is crucial for organizing Python projects:
Module: A single .py file containing Python code (functions, classes, variables).
Package: A folder containing multiple modules and an __init__.py file, which allows Python to treat it as a package.
Packages can also contain sub-packages (nested folders with their own __init__.py).
In main.py, the code tries to call my_module.say_hello("Alice").
Since there is no function named say_hello in my_module, Python will raise an AttributeError, which is a subclass of ImportError when accessed via a module. For import-specific problems, Python raises ImportError.
Which import statement correctly imports the addition module from math_ops?
When working with nested packages, Python provides two common ways to import modules:
Option 1:import my_package.math_ops.addition imports the entire module with its full namespace. Functions or classes inside are accessed like my_package.math_ops.addition.function_name().
Option 2:from my_package.math_ops import addition imports the module directly, allowing access via addition.function_name().
Option 3: Invalid syntax. You cannot use dot notation inside the from … import … statement in this way.
Example usage:
# Using Option 1
import my_package.math_ops.addition
result = my_package.math_ops.addition.add(5, 3)
# Using Option 2
from my_package.math_ops import addition
result = addition.add(5, 3)
Tip: Use Option 1 for clarity with deeply nested packages; Option 2 can simplify access when the module name is sufficient.
Tip: Avoid relying on module-level variables for persistent state across separate scripts; use files, databases, or other storage methods.
Given the following structure:
project/
main.py
utils.py
If main.py contains:
import utils
from utils import helper_function
Which statement is correct regarding how Python handles the utils module?
When a module is imported in Python, it is loaded into memory the first time it is imported. Subsequent imports of the same module, even using different forms, reference the same module object.
Example:
import utils # loads utils.py
from utils import helper_function # references the same utils module
This prevents multiple copies of the module from being created, saving memory and maintaining state.
The second import does not overwrite the first; it simply provides a direct reference to the function or variable.
Importing the same module multiple times does not raise an ImportError.
Tip: Be aware of Python’s module caching mechanism (sys.modules), which ensures modules are loaded only once per interpreter session.
Suppose you have a module config.py:
# config.py
setting = 10
You run the following in Python shell:
import config
print(config.setting) # Line 1
config.setting = 20
print(config.setting) # Line 2
import config
print(config.setting) # Line 3
What will be the output?
This exercise tests understanding of how Python handles module imports and re-imports.
Line 1: Imports config, initial setting = 10.
Line 2: Modifies config.setting to 20. This change affects the module object in memory.
Line 3: Re-importing config does not reload the module if it’s already in memory. Python uses the cached module from sys.modules, so setting remains 20.
Key points:
Python imports a module only once per interpreter session.
Changes to module-level variables persist in memory.
To force a reload, you can use import importlib; importlib.reload(config).
Output:
10 20 20
Tip: Avoid modifying module-level variables if you expect re-imports to reset them. Use functions or class instances for mutable state.
If main.py wants to import the addition module using a relative import, which statement is correct?
Relative imports are used to import modules within the same package or subpackage without specifying the full package path.
Option 1: Correct. The single dot . refers to the current package (my_package), allowing import of the submodule math_ops.addition.
Option 2: Absolute import using the full path works too, but the question specifically asks for relative import.
Option 3: Double dot .. refers to the parent package, which is invalid here since main.py is at the top level of my_package.
Option 4: Invalid unless addition.py is in the same directory as main.py.
Example usage:
from .math_ops import addition
result = addition.add(5, 3)
print(result) # 8
Tip: Use relative imports within packages to make your code easier to reorganize, but absolute imports are often clearer for readability in larger projects.
Consider the following package structure with potential circular imports:
project/
module_a.py
module_b.py
Contents:
# module_a.py
from module_b import func_b
def func_a():
return "A"
# module_b.py
from module_a import func_a
def func_b():
return "B"
What will happen if you try to import module_a in a script?
This is a classic example of a circular import, where two modules depend on each other.
module_a imports func_b from module_b.
module_b imports func_a from module_a.
When Python tries to import module_a, it starts executing it. During execution, it encounters from module_b import func_b, which triggers loading module_b.
While loading module_b, Python again tries to import func_a from module_a. At this point, func_a is not yet defined, causing an ImportError or AttributeError.
Key points:
Circular imports occur when two or more modules depend on each other directly or indirectly.
They can often be fixed by rearranging imports, using local imports inside functions, or redesigning the code.
Tip: Avoid placing imports at the top if it creates a circular dependency. Consider importing inside the function that uses the other module.
You have a large module data_processing.py with many functions. You only need the clean_data function in your script. Which import strategy is most efficient?
When working with large modules, efficiency and readability are important.
Option 1: Imports the entire module. While it works, you load all functions and variables, which is unnecessary if you only need one function.
Option 2: Imports only the clean_data function. This is memory-efficient and keeps your namespace clean.
Option 3: Using from module import * imports all names into the current namespace. This can cause name conflicts and is not recommended.
Option 4: Aliasing the module works, but you still import everything unnecessarily.
Example usage:
from data_processing import clean_data
cleaned = clean_data(raw_data)
Tip: For better efficiency and maintainability, always import only what you need from large modules.
You have two modules:
# module_x.py
value = 10
# module_y.py
value = 20
In your script, you write:
from module_x import *
from module_y import *
print(value)
What will be printed, and why?
This exercise highlights the risk of namespace pollution when using from module import *.
Both modules define a variable named value.
Using from module import * imports all names directly into the current namespace.
Since module_y is imported after module_x, its value overwrites module_x's value.
Therefore, print(value) outputs 20.
Better practices:
Use module prefixes to avoid conflicts: import module_x and import module_y.
You want to import the clean_data function from clean.py into train.py. Which is the correct relative import?
This is a tricky exercise involving nested packages and relative imports.
Option 1: Correct. The double dot .. refers to the parent package analytics, allowing access to the sibling subpackage preprocessing and the module clean.py.
Option 2: Incorrect. Without a proper absolute import setup, this will fail because Python needs to know the full package path.
Option 3: Works as an absolute import if analytics is in PYTHONPATH, but the question asks for relative import.
Option 4: Incorrect. modeling is a sibling to preprocessing, not its parent.
Example usage inside train.py:
from ..preprocessing.clean import clean_data
data = load_data()
cleaned = clean_data(data)
Tip: Use relative imports for internal package modules to make code relocatable and easier to maintain. Remember: . = current package, .. = parent package.
Which of the following is the best way to resolve the circular import?
Circular imports occur when two modules depend on each other directly. This can lead to ImportError or AttributeError at runtime.
Option 1: Removing a module may not be feasible; the functionality could be required.
Option 2: Using from module import * does not solve the circular import and can pollute the namespace.
Option 3: Correct. By moving the import inside the function that actually uses the other module, Python only performs the import when the function is called, avoiding the circular dependency at load time.
Option 4: Merging both modules works but may not be desirable for code organization or maintainability.
Example:
# module_a.py
def func_a():
from module_b import func_b # Import inside function
return "A uses " + func_b()
Tip: For complex packages, consider restructuring your code, using local imports, or splitting shared functions into a third module to avoid circular imports.
Quick Recap of Python Modules and Packages Concepts
If you are not clear on the concepts of Modules and Packages, you can quickly review
them
here before
practicing the exercises. This recap highlights the essential points and logic to help you solve
problems
confidently.
What is a Module in Python?
A module is simply a .py file containing Python code — definitions of variables, functions, classes, etc.
Once you create a module file (say, my_module.py), you can use its contents from another file by using the import statement:
import my_module
my_module.some_function()
This helps you reuse code without rewriting it.
A module helps encapsulate a set of related functionality — so modules help organize your code logically.
What is a Package in Python — and Why Use It?
A package is a directory (folder) that groups together multiple modules (and possibly sub-packages) into a cohesive unit.
To make a directory a package, you typically include a special file named __init__.py. This tells Python that the directory should be treated as a package.
Packages give you a hierarchical structure — you can organize code by functionality, feature set, or project component. This helps manage complexity when your project grows.
With packages, you can have sub-packages (nested directories), allowing deep organization of modules.
Why Modules & Packages Matter — Their Benefits
Using modules and packages wisely gives your code many advantages:
Modularity & Maintainability — By splitting code into separate modules/packages, you can work on one part independently without affecting others. This reduces bugs and simplifies maintenance.
Reusability — Once you write a module or package, you can reuse it across different projects or different parts of the same project. No need to rewrite code.
Namespace Management — Modules/packages introduce separate namespaces; this helps avoid naming conflicts when your codebase grows or when you integrate multiple external libraries.
Scalability — As your project grows, using packages helps keep it organized. Projects with many features become easier to manage.
Basic Usage Examples
Creating a module — e.g., utils.py
# utils.py
def greet(name):
print("Hello, " + name + "!")
from my_package import math_utils
print(math_utils.add(5, 3)) # Output: 8
Key Points to Remember
Concept
Description
Module
a .py file containing Python code (functions, classes, variables).
Package
a folder with one or more modules (and possibly sub-packages), with an __init__.py file.
Import statement
Use import or from … import … to access module/package contents.
Benefits
Modules and packages help you write modular, maintainable, reusable, and scalable code.
Project growth
As your Python projects grow, proper use of modules & packages becomes increasingly important for good structure and clarity.
Test Your Python Modules and Packages Knowledge
Practicing Python Modules and Packages? Don’t forget to test yourself later in
our
Python Quiz.
About This Exercise: Python – Modules and Packages
Welcome to Solviyo’s Python – Modules and Packages exercises, a practical collection designed to help learners understand how Python organizes and reuses code. In this section, we focus on the core ideas behind modules, packages, importing, structuring files, and working with Python’s built-in and user-defined modules. These exercises come with clear explanations and answers so you can learn confidently and understand every concept step by step.
What You Will Learn
Through these exercises, you will explore the essential building blocks that make Python projects organized and scalable, including:
Understanding what modules are and how they help break large programs into smaller, manageable files.
Working with import statements, including import, from ... import, and import as, and learning when each style is most useful.
Creating your own modules and using them across multiple Python files to encourage reusable and clean code.
Learning how packages work, how they are structured with folders, and the purpose of the __init__.py file.
Exploring Python’s standard library modules such as os, math, and random through hands-on exercises with explanation and answers.
Understanding Python’s module search path and how Python locates the files you import.
These exercises are designed to be approachable but practical, helping you understand not just how modules and packages work, but why they are an essential part of professional Python development.
Why Learning Modules and Packages Matters
As your Python projects grow, organizing your code becomes more important than writing it. Modules and packages give you the structure needed to write cleaner, faster, and more maintainable programs. They help you avoid repetitive code, simplify debugging, and make collaboration easier. Whether you’re preparing for interviews, learning Python for work, or becoming comfortable with larger projects, mastering modules and packages is an essential step. Our exercises, MCQs, explanations, and answers help you build these skills in a simple, practical way.
Start Strengthening Your Python Skills
With Solviyo’s Modules and Packages exercises, you can learn how Python applications are structured in the real world. These hands-on tasks and MCQs with explanations will help you understand how to import, organize, and use code efficiently. By practicing regularly, you will develop a strong grasp of Python’s modular system and be better prepared for advanced topics, larger projects, and professional development work.
Need a Quick Refresher?
Jump back to the Python Cheat Sheet to review concepts before solving more challenges.