Thursday, October 8, 2026

Python Modules and Packages

 

Python Modules and Packages – Organize Your Python Programs Like a Pro

When Python programs become bigger, putting everything into one file can make the code difficult to understand, maintain, and reuse.

Imagine you have a school bag containing books for Maths, Science, English, and Computer Science. Would you put everything into one notebook?

Probably not!

You would keep different subjects in different notebooks and organize them properly.

Python provides Modules and Packages to do exactly the same thing with programs.

In this Python Pebbles tutorial, we will learn:

  • What is a module?

  • How import works

  • from ... import

  • Built-in modules

  • The math module

  • The random module

  • The datetime module

  • The os module

  • The statistics module

  • How to create your own module

  • What are packages?

  • How to install packages using pip

  • Practice questions

  • Mini challenges

  • A master project


1. What is a Module?

A module is simply a Python file containing Python code.

A module can contain:

  • Variables

  • Functions

  • Classes

  • Statements

A Python module normally has the extension:

.py

For example:

calculator.py

can contain:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

Now another Python program can use these functions instead of writing them again.

Think of a module as a toolbox

Imagine you have a toolbox containing:

hammer
screwdriver
spanner
pliers

Instead of carrying every tool separately, you carry the toolbox.

Similarly, a Python module can contain a collection of useful functions.

calculator.py
       |
       +-- add()
       +-- subtract()
       +-- multiply()
       +-- divide()

Other Python programs can use these functions.


2. Why Do We Need Modules?

Modules provide several advantages.

1. Code Reusability

Write a function once and use it in multiple programs.

2. Better Organization

Large programs can be divided into smaller files.

3. Easier Maintenance

If something needs to be changed, you can modify the appropriate module.

4. Avoid Repeating Code

You don't need to write the same functions again and again.

5. Collaboration

Different programmers can work on different modules.


3. The import Statement

Python provides the import statement to use a module.

For example:

import math

Now we can use functions available inside the math module.

import math

print(math.sqrt(25))

Output:

5.0

Notice the syntax:

module_name.function_name()

Here:

math.sqrt()

means:

Use the sqrt() function from the math module.


4. Importing More Than One Module

We can import multiple modules.

import math
import random
import statistics

Now all three modules are available to our program.


5. Importing a Module with an Alias

Sometimes a module name can be long.

We can give it another name using as.

import statistics as stats

Now we can write:

print(stats.mean([10, 20, 30]))

Output:

20

The general syntax is:

import module_name as short_name

For example:

import math as m

print(m.sqrt(81))

Output:

9.0

6. from ... import

Sometimes we don't want to import the entire module.

We can import a particular function.

For example:

from math import sqrt

Now we can directly use:

print(sqrt(49))

Output:

7.0

Notice that we don't need:

math.sqrt()

We can simply write:

sqrt()

7. Importing Multiple Functions

We can import multiple functions.

from math import sqrt, factorial, ceil

Example:

print(sqrt(64))
print(factorial(5))
print(ceil(4.2))

Output:

8.0
120
5

8. import vs from ... import

Let's compare.

Using import

import math

print(math.sqrt(100))

Using from ... import

from math import sqrt

print(sqrt(100))

Both produce:

10.0

Python Pebble

Using:

import math

makes it very clear where sqrt() came from:

math.sqrt()

This can make larger programs easier to understand.


9. Built-in Modules

Python comes with a large collection of modules.

These are often called standard library modules.

You don't normally need to install them separately.

Some useful modules are:

ModuleCommon Use
mathMathematical operations
randomRandom numbers and choices
datetimeDates and time
osOperating-system operations
statisticsStatistical calculations

Let's explore them one by one.


10. The math Module

The math module provides many mathematical functions and constants.

First:

import math

Square Root

print(math.sqrt(81))

Output:

9.0

Power

print(math.pow(2, 5))

Output:

32.0

Factorial

print(math.factorial(5))

Output:

120

Because:

5! = 5 × 4 × 3 × 2 × 1

Ceiling

ceil() rounds a number upward.

print(math.ceil(4.2))

Output:

5

Floor

floor() rounds a number downward.

print(math.floor(4.9))

Output:

4

Mathematical Constants

Python provides useful constants.

print(math.pi)

Output will be approximately:

3.141592653589793

Example:

radius = 5

area = math.pi * radius * radius

print("Area =", area)

11. The random Module

Computers normally generate pseudo-random values.

Python provides the random module for generating random values.

Start with:

import random

Generate a Random Number

print(random.randint(1, 10))

Possible output:

7

Another run could produce:

3

The result can change each time.


Random Number Between Two Values

number = random.randint(100, 999)

print(number)

This generates a random integer between 100 and 999, inclusive.


Random Choice

Suppose we have:

colors = ["Red", "Green", "Blue", "Yellow"]

We can randomly select one:

print(random.choice(colors))

Possible output:

Blue

Randomly Select a Student

students = ["Raman", "Aman", "Riya", "Neha"]

winner = random.choice(students)

print("Winner:", winner)

Possible output:

Winner: Riya

Shuffle a List

numbers = [1, 2, 3, 4, 5]

random.shuffle(numbers)

print(numbers)

Possible output:

[3, 1, 5, 2, 4]

The order may be different every time.

Mini Challenge

Create a program that randomly selects one number from:

1 to 100

and prints:

Lucky Number: <number>

12. The datetime Module

The datetime module is used for working with:

  • Dates

  • Times

  • Date and time calculations

Import it:

import datetime

Get Current Date and Time

now = datetime.datetime.now()

print(now)

Possible output:

2026-10-08 15:30:25.123456

The exact result depends on when the program is executed.


Get Today's Date

today = datetime.date.today()

print(today)

Possible output:

2026-10-08

Extract Year, Month and Day

today = datetime.date.today()

print("Year:", today.year)
print("Month:", today.month)
print("Day:", today.day)

Create a Specific Date

birthday = datetime.date(2012, 8, 15)

print(birthday)

Output:

2012-08-15

Calculate Difference Between Dates

today = datetime.date.today()
exam_date = datetime.date(2026, 12, 1)

remaining = exam_date - today

print("Days remaining:", remaining.days)

This is useful for creating:

  • Exam countdowns

  • Birthday reminders

  • Project deadlines

  • Event countdowns

Python Pebble

Dates can be subtracted to calculate the difference between them.


13. The os Module

The os module allows Python to interact with the operating system.

Import it:

import os

It can be used for tasks such as:

  • Working with folders

  • Checking files

  • Getting the current directory

  • Creating directories

  • Listing directory contents


Current Working Directory

print(os.getcwd())

getcwd() means:

Get Current Working Directory

Possible output:

C:\Users\Student\PythonProjects

List Files and Folders

print(os.listdir())

Possible output:

['program.py', 'data.txt', 'images', 'projects']

Create a Folder

os.mkdir("PythonProjects")

This creates a folder named:

PythonProjects

Be careful: if the folder already exists, Python will raise an error.


Check Whether a File Exists

import os

if os.path.exists("data.txt"):
    print("File exists")
else:
    print("File does not exist")

This is extremely useful in real-world programs.


14. The statistics Module

The statistics module provides common statistical functions.

Import it:

import statistics

Mean

The mean is the average.

marks = [70, 80, 90, 60, 100]

print(statistics.mean(marks))

Output:

80

Median

numbers = [10, 20, 30, 40, 50]

print(statistics.median(numbers))

Output:

30

Mode

Mode is the value that occurs most frequently.

numbers = [10, 20, 20, 30, 20, 40]

print(statistics.mode(numbers))

Output:

20

Complete Example

import statistics

marks = [78, 85, 92, 67, 88]

print("Mean:", statistics.mean(marks))
print("Median:", statistics.median(marks))
print("Mode:", statistics.mode(marks))

15. Creating Your Own Module

One of the most useful features of Python is that you can create your own modules.

Suppose we create a file:

calculator.py

Add:

def add(a, b):
    return a + b


def subtract(a, b):
    return a - b


def multiply(a, b):
    return a * b


def divide(a, b):
    return a / b

Now create another file:

main.py

We can import our module:

import calculator

Then:

print(calculator.add(10, 5))
print(calculator.subtract(10, 5))
print(calculator.multiply(10, 5))
print(calculator.divide(10, 5))

Output:

15
5
50
2.0

16. Understanding the Folder Structure

Our project may look like this:

MyProject/
│
├── main.py
└── calculator.py

calculator.py is our module.

main.py is the program that uses it.

This is the beginning of writing well-organized Python programs.


17. Importing Specific Functions from Your Module

Instead of:

import calculator

print(calculator.add(10, 20))

we can write:

from calculator import add

print(add(10, 20))

Output:

30

We can also import multiple functions:

from calculator import add, multiply

print(add(5, 10))
print(multiply(5, 10))

18. The __name__ Check

You may see this statement in Python modules:

if __name__ == "__main__":

For example:

def add(a, b):
    return a + b


if __name__ == "__main__":
    print(add(10, 20))

This allows us to run some code only when the file is executed directly.

It will not run that section when the module is imported by another program.

Python Pebble

Think of it as:

"Run this part only when I am the main program."

This becomes especially useful when creating reusable modules.


19. What is a Package?

A package is a way of organizing multiple Python modules.

Think about the difference:

Module
   ↓
One Python file

while:

Package
   ↓
Folder
   ├── module1.py
   ├── module2.py
   └── module3.py

A package helps organize larger projects.


20. Example of a Package

Suppose we create:

school/
│
├── maths.py
├── science.py
└── english.py

The folder school can be used to organize modules related to school subjects.

For example:

maths.py

def square(n):
    return n * n

science.py

def gravity():
    return 9.8

We can import them using:

from school import maths

print(maths.square(5))

Output:

25

Or:

from school.maths import square

print(square(8))

Output:

64

21. Package Structure

A larger project could look like:

MyProject/
│
├── main.py
│
└── school/
    ├── __init__.py
    ├── maths.py
    ├── science.py
    └── english.py

The __init__.py file has traditionally been used to identify a directory as a Python package.

Modern Python also supports namespace packages, so __init__.py is not always required. For beginners, however, it is useful to understand it as part of the traditional package structure.


22. Installing Packages with pip

Python has a huge ecosystem of third-party packages.

Examples include packages for:

  • Data analysis

  • Machine learning

  • Web development

  • Automation

  • Visualization

  • Artificial intelligence

  • Scientific computing

One of the most common tools used to install Python packages is:

pip

23. What is pip?

pip is Python's package installer.

It allows us to install packages from the Python Package Index, commonly known as PyPI.

For example:

pip install requests

This installs the requests package.

Then we can use it in Python:

import requests

24. Installing Popular Python Packages

For example:

pip install numpy
pip install pandas
pip install matplotlib
pip install yfinance

These packages are commonly used in data analysis, visualization, finance and other Python applications.


25. Checking Installed Packages

You can use:

pip list

This displays packages installed in your Python environment.

You can also check a particular package:

pip show numpy

26. Upgrading a Package

To upgrade a package:

pip install --upgrade numpy

27. Uninstalling a Package

To remove a package:

pip uninstall numpy

Python will normally ask for confirmation before uninstalling it.


28. Installing Packages in Google Colab

If you are working in Google Colab, you can install packages using:

!pip install package_name

For example:

!pip install yfinance

After installation:

import yfinance as yf

Python Pebble

The ! tells a Colab/Jupyter notebook to execute the command through the system shell rather than as normal Python syntax.


29. Module vs Package

Let's make the difference crystal clear.

FeatureModulePackage
Basic ideaPython fileCollection of modules
Usually.py fileDirectory/folder
PurposeOrganize reusable codeOrganize larger collections of code
Examplecalculator.pyschool/
Can containFunctions, classes, variablesMultiple modules

Think:

Module = Notebook
Package = School Bag containing multiple notebooks

30. Standard Library vs Third-Party Packages

This is an important distinction.

Standard Library

These are provided with Python.

Examples:

import math
import random
import datetime
import os
import statistics

You normally don't install these using pip.

Third-Party Packages

These are developed and distributed separately.

Examples:

numpy
pandas
matplotlib
requests
yfinance

These may need to be installed using:

pip install package_name

31. Real-World Example – Student Marks Analyzer

Let's combine modules.

import statistics
import random

marks = [78, 85, 92, 67, 88]

average = statistics.mean(marks)

print("Marks:", marks)
print("Average:", average)

print("Lucky Number:", random.randint(1, 100))

Possible output:

Marks: [78, 85, 92, 67, 88]
Average: 82
Lucky Number: 47

We have used two modules in one program.


32. Real-World Example – Exam Countdown

import datetime

today = datetime.date.today()

exam_date = datetime.date(2026, 12, 1)

days_left = exam_date - today

print("Today:", today)
print("Exam Date:", exam_date)
print("Days Left:", days_left.days)

This could become the foundation of a useful Exam Countdown App.


33. Real-World Example – Random Quiz Question

Suppose we have:

import random

questions = [
    "What is Python?",
    "What is a variable?",
    "What is a module?",
    "What is a package?"
]

question = random.choice(questions)

print("Today's Question:")
print(question)

Every time the program runs, a different question may be selected.


34. A Simple Module-Based Project

Let's build a small project.

Project: Student Utility Toolkit

Folder structure:

StudentToolkit/
│
├── main.py
└── student_utils.py

student_utils.py

def percentage(marks):
    return sum(marks) / len(marks)


def highest(marks):
    return max(marks)


def lowest(marks):
    return min(marks)

main.py

import student_utils

marks = [85, 92, 76, 88, 95]

print("Average:", student_utils.percentage(marks))
print("Highest:", student_utils.highest(marks))
print("Lowest:", student_utils.lowest(marks))

Output:

Average: 87.2
Highest: 95
Lowest: 76

Congratulations!

You have just created your own reusable Python module.


35. Common Mistakes

Mistake 1: Wrong module name

import maths

when you actually wanted:

import math

Python module names must be correct.


Mistake 2: Forgetting the module name

If you write:

import math

print(sqrt(25))

you may get an error because sqrt was not imported directly.

Correct:

print(math.sqrt(25))

Or:

from math import sqrt

print(sqrt(25))

Mistake 3: Installing a standard library module

You don't normally need:

pip install math

because math is already part of Python's standard library.


Mistake 4: Naming your file after a standard module

Avoid naming your own files:

math.py
random.py
statistics.py
os.py

because your file may interfere with Python's standard modules.

Prefer names such as:

my_math.py
student_tools.py
quiz_utils.py

36. Practice Time

Level 1 – Beginner

Q1

What is a Python module?

Q2

Which statement is used to import a module?

Q3

Write the statement to import the math module.

Q4

Write a program to find the square root of 144.

Q5

Which module can be used to generate random numbers?

Q6

Write a program to generate a random number between 1 and 50.

Q7

Which module is used for dates and time?

Q8

Which module can be used to calculate the mean of a list?

Q9

What does pip do?

Q10

What is the difference between a module and a package?


37. Level 2 – Coding Practice

Q11

Write a program using math to calculate the area of a circle.

Input:

Radius = 7

Q12

Generate five random numbers between 1 and 100.


Q13

Create a program that randomly selects one student from:

["Aman", "Riya", "Raman", "Neha", "Arjun"]

Q14

Write a program that calculates the number of days between two dates.


Q15

Use the statistics module to calculate:

  • Mean

  • Median

  • Mode

for:

[10, 20, 20, 30, 40, 20]

38. Level 3 – Create Your Own Module

Create a module:

calculator.py

with these functions:

add()
subtract()
multiply()
divide()

Then create:

main.py

and import the functions.


39. Master Challenge – Student Result Analyzer

Create a Python project using modules.

Requirements

Create:

StudentResult/
│
├── main.py
└── result_utils.py

The module should contain functions for:

average()
highest()
lowest()
percentage()
grade()

The main program should:

  1. Accept marks for five subjects.

  2. Calculate total marks.

  3. Calculate percentage.

  4. Find highest marks.

  5. Find lowest marks.

  6. Calculate average.

  7. Assign a grade.

  8. Display the result.

Bonus Challenge

Add:

random

to generate sample marks for testing.


40. Quick Revision

ConceptRemember
ModulePython file containing reusable code
importImports a module
from ... importImports selected items
mathMathematical functions
randomRandom values and choices
datetimeDate and time
osOperating-system interaction
statisticsStatistical calculations
Own moduleA .py file created by you
PackageCollection/organization of modules
pipPython package installer

41. Python Pebble 🪨

Don't write the same code again and again.

Put reusable code into a module and use it whenever you need it.

A good Python programmer doesn't just ask:

"How do I make this program work?"

A better question is:

"How can I organize this code so that I can reuse it later?"

That is where Modules and Packages become powerful.


42. What You Learned

In this tutorial, you learned:

✅ What a module is
✅ How import works
✅ How from ... import works
✅ Built-in Python modules
✅ math
✅ random
✅ datetime
✅ os
✅ statistics
✅ Creating your own module
✅ Packages
✅ Installing packages using pip
✅ Using modules in real-world projects

The next time your Python program becomes too large, don't put everything into one file.

Break it into modules. Organize modules into packages. Reuse your code.

That's how small Python programs gradually become well-structured software projects.

No comments:

Post a Comment

Python Algorithms

  Python Algorithms for Beginners – Searching, Sorting and Essential Problem-Solving Techniques Learn Linear Search, Binary Search, Sorting ...