Modules and Packages: Organize Your Code Like a Pro — Python Course #7
Introduction: Why Organize Your Code into Modules

Welcome to part 7 of 10 of our Python course for beginners. Until now, we have been writing all our code in a single file. That works fine for small scripts, but imagine having a program with 5,000 lines of code... it would be chaos trying to find anything.
Modules are the solution. A module is simply a .py file that contains functions, variables, and classes you can reuse in other files. It is like organizing your clothes into drawers: instead of having everything piled up, each drawer has a purpose.
In this article you will learn to:
- Import modules that come built into Python
- Create your own modules
- Use the most useful standard library modules
- Install external packages with pip
- Create virtual environments for your projects
What Is a Module and How to Import It
A module in Python is any file with a .py extension. When you write import module_name, Python finds that file and gives you access to everything it contains.
There are two main ways to import:
Method 1: Full import
1# We import the entire math module
2import math
3
4# To use something, we write module.function
5result = math.sqrt(25)
6print(result) # 5.0
Method 2: from ... import (import something specific)
1# We only import the sqrt function
2from math import sqrt
3
4# Now we use it directly, without the "math." prefix
5result = sqrt(25)
6print(result) # 5.0
Import multiple things at once
1from math import sqrt, pi, ceil
2
3print(sqrt(16)) # 4.0
4print(pi) # 3.141592653589793
5print(ceil(4.2)) # 5
Give an alias to a module
1# "as" lets you give the module a short name
2import math as m
3
4print(m.sqrt(9)) # 3.0
5print(m.pi) # 3.141592653589793
from module import * (import everything). It can cause conflicts if two modules have functions with the same name. It is always better to be explicit about what you import.
Create Your Own Module
Creating a module is as simple as creating a .py file with functions. Let us see an example step by step:
Step 1: Create a file called greetings.py
1# greetings.py - This is our custom module
2
3def hello(name):
4 """Greet someone by their name."""
5 return f"Hello, {name}! Welcome."
6
7def goodbye(name):
8 """Say goodbye to someone."""
9 return f"Goodbye, {name}! See you soon."
10
11def formal_greeting(name, title="Mr."):
12 """Formal greeting with a title."""
13 return f"Dear {title} {name}, it is a pleasure to greet you."
Step 2: Use your module from another file
1# main.py - Main file (must be in the same folder)
2
3import greetings
4
5print(greetings.hello("Ana"))
6# Hello, Ana! Welcome.
7
8print(greetings.goodbye("Carlos"))
9# Goodbye, Carlos! See you soon.
10
11# You can also import specific functions
12from greetings import formal_greeting
13
14print(formal_greeting("Garcia", "Dr."))
15# Dear Dr. Garcia, it is a pleasure to greet you.
The math Module: Useful Math Functions
The math module comes built into Python and has math functions you will use frequently. You do not need to install anything, just import it.
1import math
2
3# Square root
4print(math.sqrt(144)) # 12.0
5
6# Round up (ceil) and round down (floor)
7print(math.ceil(4.1)) # 5 (goes up to the next integer)
8print(math.floor(4.9)) # 4 (goes down to the previous integer)
9
10# The number Pi
11print(math.pi) # 3.141592653589793
12
13# Power
14print(math.pow(2, 10)) # 1024.0 (2 raised to the power of 10)
15
16# Absolute value (for decimal numbers)
17print(math.fabs(-7.5)) # 7.5
18
19# Factorial (useful in combinatorics)
20print(math.factorial(5)) # 120 (5 x 4 x 3 x 2 x 1)
Practical example: calculate the area of a circle
1import math
2
3def circle_area(radius):
4 """Calculate the area of a circle given its radius."""
5 return math.pi * math.pow(radius, 2)
6
7# Let us try with a circle of radius 5
8radius = 5
9area = circle_area(radius)
10print(f"The area of a circle with radius {radius} is: {area:.2f}")
11# The area of a circle with radius 5 is: 78.54
The random Module: Generate Random Numbers
The random module lets you generate random numbers, pick random elements from a list, and shuffle data. It is very useful for games, simulations, and testing.
1import random
2
3# Random integer between 1 and 10 (includes both)
4print(random.randint(1, 10)) # Example: 7
5
6# Random decimal between 0.0 and 1.0
7print(random.random()) # Example: 0.6543
8
9# Pick a random element from a list
10fruits = ["apple", "banana", "orange", "grape", "strawberry"]
11print(random.choice(fruits)) # Example: "orange"
12
13# Pick several random elements (without repeating)
14print(random.sample(fruits, 3)) # Example: ["grape", "apple", "strawberry"]
15
16# Shuffle a list (modifies it directly)
17numbers = [1, 2, 3, 4, 5]
18random.shuffle(numbers)
19print(numbers) # Example: [3, 1, 5, 2, 4]
Practical example: simulate rolling a dice
1import random
2
3def roll_dice():
4 """Simulate rolling a 6-sided dice."""
5 return random.randint(1, 6)
6
7# Roll the dice 5 times
8print("Results of 5 rolls:")
9for i in range(5):
10 result = roll_dice()
11 print(f" Roll {i + 1}: {result}")
random.seed(42) at the beginning. This makes the sequence reproducible.
The datetime Module: Working with Dates and Times
The datetime module lets you work with dates, times, and do calculations like finding out how many days are left until a certain date.
1from datetime import datetime, date, timedelta
2
3# Current date and time
4now = datetime.now()
5print(now) # 2026-04-05 14:30:00.123456
6
7# Just today's date
8today = date.today()
9print(today) # 2026-04-05
10
11# Create a specific date
12christmas = date(2026, 12, 25)
13print(christmas) # 2026-12-25
14
15# Calculate how many days are left
16difference = christmas - today
17print(f"{difference.days} days until Christmas")
Format dates as text
1from datetime import datetime
2
3now = datetime.now()
4
5# strftime = "string format time" (converts date to text)
6print(now.strftime("%d/%m/%Y")) # 05/04/2026
7print(now.strftime("%B %d, %Y")) # April 05, 2026
8print(now.strftime("%H:%M:%S")) # 14:30:00
9print(now.strftime("%A")) # Sunday
Add and subtract days
1from datetime import date, timedelta
2
3today = date.today()
4
5# Add 30 days
6in_one_month = today + timedelta(days=30)
7print(f"Today: {today}")
8print(f"In 30 days: {in_one_month}")
9
10# Subtract 7 days
11one_week_ago = today - timedelta(days=7)
12print(f"One week ago: {one_week_ago}")
The os Module: Interact with the Operating System
The os module lets you interact with the operating system: view files, create folders, get paths, and more.
1import os
2
3# See the current working directory
4print(os.getcwd())
5# Example: /home/user/my-project
6
7# List files and folders in the current directory
8files = os.listdir(".")
9print(files)
10# Example: ['main.py', 'greetings.py', 'data']
11
12# Check if a file or folder exists
13print(os.path.exists("main.py")) # True
14print(os.path.exists("no_exists.py")) # False
15
16# Create a new folder
17if not os.path.exists("my_folder"):
18 os.mkdir("my_folder")
19 print("Folder created")
20
21# Join paths safely (works on Windows and Linux)
22path = os.path.join("my_folder", "file.txt")
23print(path) # my_folder/file.txt
Practical example: list only Python files
1import os
2
3def list_python_files(directory="."):
4 """List all .py files in a directory."""
5 files = os.listdir(directory)
6 py_files = [f for f in files if f.endswith(".py")]
7 return py_files
8
9# Show Python files in the current directory
10for file in list_python_files():
11 size = os.path.getsize(file)
12 print(f" {file} ({size} bytes)")
os.remove() or os.rmdir(). They delete files and folders permanently, without going to the recycle bin.
Install External Packages with pip
Python has thousands of community-created packages you can install easily. pip is the Python package manager (it comes included when you install Python).
Basic pip commands
1# Install a package
2pip install requests
3
4# Install a specific version
5pip install requests==2.31.0
6
7# See installed packages
8pip list
9
10# See information about a package
11pip show requests
12
13# Save the list of packages to a file
14pip freeze > requirements.txt
15
16# Install all packages from a file
17pip install -r requirements.txt
18
19# Uninstall a package
20pip uninstall requests
Example: install and use the requests package
1# First install: pip install requests
2
3import requests
4
5# Make an HTTP request to a public API
6response = requests.get("https://api.github.com")
7
8print(f"Status: {response.status_code}") # 200
9print(f"Type: {response.headers['content-type']}")
10
11# View the data as JSON
12data = response.json()
13print(f"Current user URL: {data['current_user_url']}")
pip freeze > requirements.txt to save your project dependencies. This way anyone can install the exact same packages with pip install -r requirements.txt.
Virtual Environments with venv
A virtual environment is an isolated copy of Python for each project. Why do you need this? Imagine you have two projects:
- Project A needs
requests 2.28 - Project B needs
requests 2.31
If you install everything in the same place, one of the two projects will break. Virtual environments solve this: each project has its own independent set of packages.
Create and activate a virtual environment
1# Step 1: Create the virtual environment (only once per project)
2python -m venv my_env
3
4# Step 2: Activate the virtual environment
5
6# On Windows:
7my_envScriptsactivate
8
9# On macOS/Linux:
10source my_env/bin/activate
11
12# You will see your terminal change, showing the environment name:
13# (my_env) user@pc:~$
14
15# Step 3: Install packages (they install ONLY in this environment)
16pip install requests
17pip install flask
18
19# Step 4: Save the dependencies
20pip freeze > requirements.txt
21
22# Step 5: Deactivate the environment when you are done
23deactivate
Recommended workflow
1# 1. Create project folder
2mkdir my_project
3cd my_project
4
5# 2. Create virtual environment
6python -m venv venv
7
8# 3. Activate
9source venv/bin/activate # Linux/Mac
10venvScriptsactivate # Windows
11
12# 4. Install dependencies
13pip install requests flask
14
15# 5. Save dependencies
16pip freeze > requirements.txt
17
18# 6. Work on your project...
19python main.py
20
21# 7. When you are done
22deactivate
venv/ to your .gitignore file. Only share the requirements.txt file.
Practical Example: Reusable Utilities Module
Let us create a complete module with useful functions you can reuse in any project. This example combines everything we learned:
File: utilities.py
1# utilities.py - Reusable utilities module
2
3import os
4import random
5import string
6from datetime import datetime, date
7
8# === Text functions ===
9
10def clean_text(text):
11 """Remove extra spaces and convert to lowercase."""
12 return " ".join(text.split()).strip().lower()
13
14def generate_password(length=12):
15 """Generate a secure random password."""
16 characters = string.ascii_letters + string.digits + "!@#$%"
17 password = "".join(random.choice(characters) for _ in range(length))
18 return password
19
20def count_words(text):
21 """Count the words in a text."""
22 words = text.split()
23 return len(words)
24
25# === Date functions ===
26
27def days_between_dates(date1, date2):
28 """Calculate the days between two dates (format: 'YYYY-MM-DD')."""
29 d1 = datetime.strptime(date1, "%Y-%m-%d").date()
30 d2 = datetime.strptime(date2, "%Y-%m-%d").date()
31 difference = abs((d2 - d1).days)
32 return difference
33
34def is_weekend():
35 """Return True if today is Saturday or Sunday."""
36 day = date.today().weekday()
37 return day >= 5 # 5=Saturday, 6=Sunday
38
39# === File functions ===
40
41def list_files(directory=".", extension=None):
42 """List files in a directory, optionally filtering by extension."""
43 files = os.listdir(directory)
44 if extension:
45 files = [f for f in files if f.endswith(extension)]
46 return sorted(files)
47
48def readable_size(size_bytes):
49 """Convert bytes to a readable format (KB, MB, GB)."""
50 for unit in ["B", "KB", "MB", "GB"]:
51 if size_bytes < 1024:
52 return f"{size_bytes:.1f} {unit}"
53 size_bytes /= 1024
54 return f"{size_bytes:.1f} TB"
File: main.py (using our module)
1# main.py - Testing our utilities module
2
3from utilities import (
4 clean_text,
5 generate_password,
6 count_words,
7 days_between_dates,
8 is_weekend,
9 list_files,
10 readable_size,
11)
12
13# --- Text functions ---
14text = " Hello World PYTHON "
15print(f"Clean text: '{clean_text(text)}'")
16# Clean text: 'hello world python'
17
18print(f"Generated password: {generate_password(16)}")
19# Generated password: aB3$kL9mNp2@xYqR
20
21article = "Python is a very popular programming language"
22print(f"Words in the article: {count_words(article)}")
23# Words in the article: 7
24
25# --- Date functions ---
26days = days_between_dates("2026-01-01", "2026-12-31")
27print(f"Days between the dates: {days}")
28# Days between the dates: 364
29
30print(f"Is it the weekend? {'Yes' if is_weekend() else 'No'}")
31
32# --- File functions ---
33py_files = list_files(".", ".py")
34print(f"Python files: {py_files}")
35
36print(f"1,500,000 bytes = {readable_size(1_500_000)}")
37# 1,500,000 bytes = 1.4 MB
utils/ with several modules inside (text.py, dates.py, files.py) and an empty __init__.py file to turn it into a package. This helps you organize your code better in large projects.
Summary and Next Article
In this article you learned how to organize your Python code like a professional:
- Modules: reusable
.pyfiles that you can import withimport - math: mathematical functions like
sqrt,ceil,floor, andpi - random: random numbers, random picks, and list shuffling
- datetime: work with dates, calculate differences, and format them
- os: interact with system files and folders
- pip: install community Python packages
- venv: create isolated virtual environments for each project
In the next article (part 8 of 10) we will learn Object-Oriented Programming (OOP): classes, objects, inheritance, and everything you need to write more organized and professional code. Do not miss it!
Comments
Sign in to leave a comment
No comments yet. Be the first!