Learning Python for Beginners — Part 8
By Data Impala
Welcome back to our Python learning journey at Data Impala!
In our last article, you learned how to handle errors and exceptions in Python.
Now it’s time to level up your code organization game.
As your programs grow bigger, you’ll notice that stuffing everything into one giant file becomes overwhelming.
That’s where modules and packages come into play. They help you write clean, manageable, and reusable code.
Let’s walk through this step by step.
Table of Contents
What Is a Python Module?
A module in Python is just a .py file containing Python code—functions, variables, or classes—that you can reuse in other Python files.
It helps you keep your code DRY (Don’t Repeat Yourself).
A Python module file can be identified by a .py extension. This file can include functions, variables, classes, or even runnable code.
When you save your code in a module, you can import it into another Python program to reuse its functionality.
For example:
# greetings.py — This is a module
def say_hello(name):
return f"Hello, {name}!"
def say_goodbye(name):
return f"Goodbye, {name}!"
You can now use this module in another Python script like this:
# main.py
import greetings
print(greetings.say_hello("Ahnaf")) # Output: Hello, Ahnaf!
print(greetings.say_goodbye("Ahnaf")) # Output: Goodbye, Ahnaf!
Example: Creating a Module
# math_tools.py
def add(x, y):
return x + y
def subtract(x, y):
return x - y
This file is now a module. You can use it in another script like this:
# main.py
import math_tools
print(math_tools.add(10, 5)) # Output: 15
print(math_tools.subtract(10, 3)) # Output: 7
This way, your main script stays clean, and your logic stays reusable.
What Is a Package?
A package is a folder that contains multiple module files and an __init__.py file.
That __init__.py file can be empty, but it’s required (in Python 3.2+ it’s optional but still commonly used) to tell Python, “Hey, this folder is a package!”
Folder Structure Example:
my_tools/
│
├── __init__.py
├── math_tools.py
└── string_tools.py
Now you can import modules from the package like this:
from my_tools import math_tools
print(math_tools.add(2, 3))
Or even:
from my_tools.math_tools import add
print(add(2, 3)) # Output: 5
Different Ways to Import
You can import your module in a number of ways for convenience. Here are some of the ways to do it:
1. Import the whole module
This style is straightforward and clear: you bring in the entire module and access everything through its module name.
import math_tools
math_tools.add(3, 4)
Importing the whole module is useful when the module is small and contains only a few functions or classes.
When you want to avoid confusion about where a function comes from — the module name acts as a label.
It also helps to keep the global namespace clean (you don’t want every function name from the module to appear at the top level of your script).
2. Import specific functions
This method brings in only the functions or classes you actually need, without loading the entire module.
from math_tools import add
add(3, 4)
You import specific functions when you only need one or two functions and want to keep the code concise.
Importing specific functions are also useful when working with multiple modules that may contain similarly named functions, and you’re confident there won’t be any naming confusion.
3. Rename with aliases
Here, you’re still importing the full module but giving it a shorter or more meaningful name using an alias.
import math_tools as mt
mt.subtract(10, 2)
Aliases helps to assign a shorter name to an original module with long name.
Each style has its use, but using aliases is especially handy for long module names.
Built-in Python Modules You Should Know
Python comes with many built-in modules. Here are a few that you’ll use often:
1. math – for math operations
The math module provides access to mathematical functions like square roots, trigonometry, logarithms, factorials, and constants such as pi and e.
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592...
Importance:
When you need precise and advanced math operations beyond basic arithmetic (+, -, *, /), this module is your go-to.
It’s especially helpful in scientific, engineering, and data-related work where calculations need accuracy and range.
2. random – for random numbers
The random module helps you generate random numbers and make random choices.
You can shuffle items, pick random elements, or generate random integers and floating-point numbers.
import random
print(random.randint(1, 10)) # Any number between 1 and 10
Importance:
This module is essential for simulations, games, testing, and machine learning tasks where randomness is required—like splitting datasets or adding variation to algorithms.
3. datetime – for handling dates and times
datetime deals with dates and times.
You can create, format, and manipulate dates, times, and time differences.
from datetime import date
print(date.today()) # Outputs today’s date
Importance:
The datetime module is useful when you need to timestamp events, calculate durations, schedule tasks, or manage logs.
It’s a key module in any application that works with real-world time (like reports, alarms, or logs).
4. os – for interacting with the file system
The os module interacts with your computer’s operating system.
It helps you navigate folders, create/delete files, get environment variables, and run system-level commands.
import os
print(os.getcwd()) # Shows the current working directory
Importance:
Crucial for file management and automation.
If you’re writing scripts to process files, build tools, or manage projects, this module gives you access to your computer’s file system and environment in a safe way.
Creating a Custom Package – Step by Step
Let’s build a small package to manage tasks.
1. Create Folder Structure
We begin by creating a folder named task_manager. This folder is our custom Python package.
Inside it, we create three files:
task_manager/
├── __init__.py
├── add_task.py
└── remove_task.py
But why this structure?
- task_manager/ is the package directory.
- __init__.py tells Python that this folder is a package. Even if it’s empty, Python uses it to recognize the folder as importable.
- add_task.py and remove_task.py are modules — individual Python files that hold related functions.
This structure is important because it makes your code modular. You can focus on one small piece (like adding tasks) without messing up other parts.
2. Write add_task.py
# add_task.py
def add(task, task_list):
task_list.append(task)
return task_list
What this function does:
- task: a single task, like “Learn Python”.
- task_list: the current list of all tasks.
- The function adds the new task to the list using .append() and returns the updated list.
Why do we write this in a separate file?
It keeps your code organized.
If you want to improve the add logic later (e.g., check for duplicates), you can do it here — without touching the rest of the program.
3. Write remove_task.py
# remove_task.py
def remove(task, task_list):
if task in task_list:
task_list.remove(task)
return task_list
What this function does:
- Checks if the task exists in the list using if task in task_list.
- If it does, it removes it using .remove().
- Then, it returns the updated list.
Why do it this way?
It prevents errors.
If you try to remove something not in the list, Python would normally throw an error. So we first check if the task is there.
This logic could also be extended later — for example, to log removed tasks or confirm with the user.
Keeping it in its own file makes such updates cleaner.
4. Use the package in main.py
Now you’ll create a separate file where everything comes together — main.py.
# main.py
from task_manager import add_task, remove_task
tasks = []
tasks = add_task.add("Learn Python", tasks)
tasks = remove_task.remove("Learn Python", tasks)
print(tasks) # Output: []
This small project is now modular. You can test, update, and reuse each part without touching everything else.
What happened?
Importing the modules:
from task_manager import add_task, remove_task
This tells Python to look inside the task_manager package and pull out the modules add_task and remove_task.
Creating an empty task list:
tasks = []
Adding a task:
tasks = add_task.add("Learn Python", tasks)
This calls the add() function inside add_task.py, and adds “Learn Python” to the empty list.
Removing a task:
tasks = remove_task.remove("Learn Python", tasks)
This calls the remove() function inside remove_task.py to delete the same task.
Printing the result:
print(tasks) # Output: []
Since we added and then removed the same task, the final list is empty.
Why Should You Use Modules and Packages?
- Separation of concerns: Each module does one job.
- Reusability: Write once, use everywhere.
- Simplifies debugging: Easier to isolate problems.
- Better collaboration: Teammates can work on separate modules.
- Cleaner codebase: Easy to navigate and maintain.
Practice Test: Build a Simple Calculator Package
Your Challenge: Create a calculator using packages.
Here’s what you need to do step-by-step:
- Create a folder called my_calculator.
- Inside that, add:
- __init__.py
- multiply.py
- divide.py
- Each file should contain:
- multiply(x, y) function that returns the product
- divide(x, y) function that returns the result or a message if dividing by 0
In your main file, use both functions.
Solution
Folder structure:
my_calculator/
├── __init__.py
├── multiply.py
└── divide.py
multiply.py
# multiply.py
def multiply(x, y):
return x * y
divide.py
# divide.py
def divide(x, y):
if y == 0:
return "Error: Cannot divide by zero"
return x / y
main.py
# main.py
from my_calculator import multiply, divide
print(multiply.multiply(4, 5)) # Output: 20
print(divide.divide(10, 2)) # Output: 5.0
print(divide.divide(10, 0)) # Output: Error: Cannot divide by zero
Explanation:
- The multiply() function simply multiplies two numbers.
- The divide() function checks if the divisor is zero. If not, it performs the division.
- We import the functions and test them in main.py.
Final Thoughts
Modules and packages help you stay organized as your codebase grows.
Instead of cramming everything into one file, break it into focused parts.
Once you get comfortable with this structure, your programs will be easier to read, fix, and share.
In the next lesson, we’ll learn more about Python functions, arguments, and return values.
✍️ Written by Ahnaf Chowdhury
📘 Series: Learning Python for Beginners — Part 8