A module is a Python file containing reusable code such as variables, functions, classes, or executable statements. A file ending in .py can be used as a module.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
1.2 Why use modules?
Modules help split a large program into smaller, organized, reusable files. This improves readability, maintenance, testing, and code reuse.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
1.3 Module vs script
A Python file can be run directly as a script or imported as a module. The __name__ variable helps distinguish these situations.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
1.4 Module workflow
Create a .py file, place reusable code inside it, import it from another program, then call the required functions/classes.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
TOPIC 02
2. Built-in Modules
2.1 What are built-in/standard-library modules?
Python provides a large standard library containing modules for mathematics, dates, operating-system operations, random numbers, JSON, CSV, statistics, regular expressions, and more.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
2.2 math module
The math module provides mathematical functions and constants such as sqrt(), ceil(), floor(), factorial(), pi, and pow().
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
2.3 random module
The random module generates pseudo-random values. Common functions include randint(), choice(), random(), and shuffle().
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
2.4 datetime module
datetime provides classes and functions for working with dates and times, including date, time, datetime, and timedelta.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
2.5 os module
The os module provides operating-system related functionality such as current directory, environment variables, directory creation, and path operations.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
2.6 sys module
The sys module gives access to interpreter-related information and functionality, such as command-line arguments and Python version information.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
2.7 statistics module
The statistics module provides common statistical calculations such as mean(), median(), and mode().
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
TOPIC 03
3. Importing Modules
3.1 import module
Use import module_name to load a module. Access its members with dot notation, such as math.sqrt(25).
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
3.2 import with alias
Use import module_name as alias when a shorter or clearer name is useful, such as import math as m.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
3.3 from module import
Use from module import name to import a particular member directly. Then it can be used without the module prefix.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
3.4 Import multiple members
You can import several named members using commas, but avoid unnecessary imports because they can reduce clarity.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
3.5 Avoid wildcard imports
from module import * imports many names into the current namespace and can create naming conflicts. Explicit imports are usually better.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
3.6 Import execution
When a module is imported, Python executes its top-level statements once for that interpreter session and then reuses the loaded module.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
TOPIC 04
4. Creating User-Defined Modules
4.1 Create your own module
Create a Python file such as calculator.py and place reusable functions or classes in it.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
4.2 Import your module
Keep the module accessible on Python's import path and import it using import calculator or a suitable import statement.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
4.3 Reuse functions
Once imported, functions can be called repeatedly from other files without copying their implementation.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
4.4 __name__ and __main__
The pattern if __name__ == '__main__': allows code to run when the file is executed directly while preventing that section from running during normal import.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
4.5 Organizing modules
Group related functionality together. For example, database functions can be kept in database.py and mathematical utilities in math_utils.py.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
TOPIC 05
5. Packages
5.1 What is a package?
A package is a way to organize related modules in a directory structure. Packages make larger projects easier to navigate.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
5.2 Package structure
A package can contain modules and subpackages. Modern Python supports namespace packages, while __init__.py is still commonly used for explicit package initialization and compatibility.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
5.3 Import from a package
Use statements such as from mypackage import calculator or import mypackage.calculator depending on the project structure.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
5.4 Subpackages
A package can contain another package, allowing large applications to be organized into logical layers.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
5.5 __init__.py
__init__.py can initialize package-level behavior and expose selected names. It may also be an empty file.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
TOPIC 06
6. Module Search Path & Import Concepts
6.1 sys.path
Python searches locations listed in sys.path when resolving imports. It commonly includes the current project location and standard library locations.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
6.2 Import errors
ModuleNotFoundError generally means Python could not locate the requested module. ImportError can occur when a module exists but a requested name cannot be imported.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
6.3 Circular imports
A circular import occurs when modules depend on each other during initialization. It can cause partially initialized modules or import errors.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
6.4 Relative imports
Inside packages, relative imports such as from .utils import helper can reference modules relative to the current package.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
6.5 Good import practice
Keep imports near the top of the file, use explicit imports, avoid unnecessary wildcard imports, and structure packages to reduce circular dependencies.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
TOPIC 07
7. Installing and Using External Packages
7.1 Standard library vs external package
Standard-library modules come with Python. External packages are separately installed libraries, commonly from the Python Package Index.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
7.2 pip
pip is a package installer commonly used to install, upgrade, and remove Python packages.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
7.3 Installing a package
A typical command is python -m pip install package_name. Using python -m pip helps associate pip with the intended Python interpreter.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
7.4 requirements.txt
A requirements file records project dependencies so another environment can install the required packages.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
7.5 Virtual environments
A virtual environment creates an isolated Python environment for a project, reducing dependency conflicts between projects.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
7.6 Version management
Pin or constrain dependency versions when reproducibility matters, and keep dependencies updated responsibly.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
TOPIC 08
8. Practical Module & Package Design
8.1 Separation of responsibility
Keep each module focused. A module should have a clear purpose instead of becoming a collection of unrelated utilities.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
8.2 Reusability
Design functions and classes so they can be imported and reused without depending unnecessarily on global state.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
8.3 Documentation
Use docstrings and meaningful names to explain public modules, functions, and classes.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
8.4 Testing imported code
Keep demonstration or test execution under if __name__ == '__main__': so importing the module does not unexpectedly run the demo.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
8.5 Common mistakes
Typical mistakes include wrong filenames, incorrect import paths, wildcard imports, circular imports, installing packages into the wrong interpreter, and mixing project files with unrelated names.
Step-by-step:
Understand why the module/package concept is needed.
Study the import syntax and naming rule.
Run a small example and observe the result.
Change one part of the example and test again.
Practice the related coding question.
HANDS-ON PRACTICE
30 Coding Questions
Try each problem yourself first, then open the step-by-step solution.
Q01
Import the math module and calculate a square root.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
import math
print(math.sqrt(144))
Q02
Use a module alias.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
import math as m
print(m.pi)
print(m.sqrt(81))
Q03
Import only sqrt from math.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
from math import sqrt
print(sqrt(100))
Q04
Use math.ceil() and math.floor().
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
import math
print(math.ceil(4.2))
print(math.floor(4.8))
Q05
Calculate factorial using the math module.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
import math
print(math.factorial(5))
Q06
Generate a random integer from 1 to 100.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
import random
number = random.randint(1, 100)
print(number)
Q07
Choose a random item from a list.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
import random
colors = ["red", "blue", "green", "yellow"]
print(random.choice(colors))
Q08
Shuffle a list using random.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
from datetime import date
print(date.today())
Q10
Calculate a date after 10 days.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
from datetime import datetime
print(datetime.now())
Q12
Calculate mean and median.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
import os
print(os.getcwd())
Q14
Create a directory if it does not exist.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
import os
folder = "reports"
if not os.path.exists(folder):
os.mkdir(folder)
print("Folder ready")
Q15
Display the Python version.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
import sys
print(sys.version)
Q16
Read command-line arguments.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
import sys
print(sys.argv)
Q17
Create a user-defined calculator module.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
# calculator.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
Q18
Import functions from your calculator module.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
Import selected functions from a user-defined module.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
# calculator.py
def add(a, b):
return a + b
# main.py
from calculator import add
print(add(7, 8))
Q20
Use __name__ == '__main__'.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
def greet():
print("Hello from the module")
if __name__ == "__main__":
greet()
Q21
Create a module with a class and import it.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
# student.py
class Student:
def __init__(self, name):
self.name = name
# main.py
from student import Student
s = Student("Ravi")
print(s.name)
Q22
Create and import a package module.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
# mypackage/calculator.py
def add(a, b):
return a + b
# main.py
from mypackage.calculator import add
print(add(20, 30))
Q23
Inspect Python's module search path.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
import sys
for path in sys.path:
print(path)
Q24
Handle ModuleNotFoundError.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
try:
import unknown_module
except ModuleNotFoundError:
print("Module was not found")
Q25
Create a reusable utility module.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
Use pathlib from the standard library to list Python files.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
from pathlib import Path
for file in Path(".").glob("*.py"):
print(file)
Q28
Install an external package using pip from Python's command-line style.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
# Run this in a terminal:
# python -m pip install requests
# Then in Python:
import requests
print(requests.__version__)
Q29
Read a requirements.txt file conceptually through Python.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
from pathlib import Path
requirements = Path("requirements.txt")
if requirements.exists():
print(requirements.read_text())
else:
print("requirements.txt not found")
Q30
Build a small package-style project example.
Step 1: Identify the module or package feature required. Step 2: Write the correct import statement or module structure. Step 3: Use the imported function, class, or feature. Step 4: Run the code and verify the output.
# project/
# main.py
# utils/
# __init__.py
# calculator.py
# utils/calculator.py
def add(a, b):
return a + b
# main.py
from utils.calculator import add
print(add(100, 250))
KNOWLEDGE CHECK
30 Theory Questions with Answers
Use these for revision, interviews, and classroom practice.
Q01
What is a module?
Answer: A module is a Python file containing reusable code such as functions, classes, variables, or statements.
Q02
Why are modules useful?
Answer: They divide code into manageable, reusable units and improve organization and maintenance.
Q03
What is the difference between a module and a script?
Answer: A module is designed to be imported and reused, while a script is commonly executed directly. The same file can serve both roles.
Q04
What is the Python standard library?
Answer: It is the collection of modules distributed with Python that provides many common capabilities without separate installation.
Q05
What does import do?
Answer: import loads a module so its members can be accessed and reused in the current program.
Q06
Why use an import alias?
Answer: An alias can make long module names shorter or improve readability.
Q07
What does from module import name mean?
Answer: It imports a specific name from a module so it can be referenced directly.
Q08
Why should wildcard imports usually be avoided?
Answer: They can introduce unexpected names and naming conflicts and make code harder to understand.
Q09
What is math?
Answer: math is a standard-library module containing common mathematical functions and constants.
Q10
What is random?
Answer: random is a standard-library module for generating pseudo-random values and selecting or shuffling data.
Q11
What is datetime?
Answer: datetime is a standard-library module for working with dates, times, and time intervals.
Q12
What is os?
Answer: os provides operating-system interfaces such as directory, environment, and path-related operations.
Q13
What is sys?
Answer: sys provides access to Python interpreter information and features such as command-line arguments.
Q14
What is a user-defined module?
Answer: It is a module created by the programmer, usually as a .py file, to organize reusable project code.
Q15
What is __name__?
Answer: It is a special module variable whose value helps identify how the module is being executed or imported.
Q16
Why use if __name__ == '__main__':?
Answer: It ensures a block runs when the file is executed directly but not when the file is imported as a module.
Q17
What is a package?
Answer: A package organizes related Python modules into a directory structure.
Q18
What is __init__.py?
Answer: It is a package initialization file that can be used to initialize a package or expose selected names. It can also be empty.
Q19
What is a subpackage?
Answer: A subpackage is a package located inside another package.
Q20
What is sys.path?
Answer: It is the list of locations Python searches when resolving imports.
Q21
What is ModuleNotFoundError?
Answer: It generally occurs when Python cannot find the requested module in its available import locations.
Q22
What is ImportError?
Answer: It can occur when an import operation fails, such as when a requested name cannot be imported from a module.
Q23
What is a circular import?
Answer: It occurs when modules depend on each other through imports, creating a cycle during module initialization.
Q24
What is a relative import?
Answer: It references another module relative to the current package, such as from .utils import helper.
Q25
What is pip?
Answer: pip is a commonly used Python package installer for installing and managing external packages.
Q26
What is an external package?
Answer: It is a separately distributed library that is not part of Python's standard library.
Q27
What is requirements.txt?
Answer: It is a text file commonly used to record project dependencies and their versions or version constraints.
Q28
Why use virtual environments?
Answer: They isolate project dependencies so different projects can use different package versions without interfering with one another.
Q29
What is module reusability?
Answer: It means code written in one module can be imported and used by multiple programs without copying the implementation.
Q30
Give two good module-design practices.
Answer: Keep modules focused on a clear responsibility and expose reusable functions/classes with clear names and documentation.