Python Course
Modules and Packages in Python
In this lesson you will learn about Modules and Packages — the system Python uses to organise and share reusable code. Every serious Python project uses modules. By the end of this lesson you will know how to import built-in modules, use the Python Standard Library, install third-party packages, and create your own module.
1. What is a Module?
A module is simply a Python file — a .py file that contains functions, variables, and classes you can use in other programs. Instead of writing the same helper code in every project, you put it in a module once and import it wherever you need it.
Think of a module like a toolbox. You do not carry every tool in your pocket — you store them in a box and grab whichever one you need. Python has hundreds of built-in toolboxes (called the Standard Library) ready to use with no installation required.
Why do modules exist?
- Avoid rewriting the same code in every project
- Keep programs organised — each file has a clear purpose
- Share code between projects and with other developers
- Use Python's built-in library of pre-written, tested functions
2. Importing a Module
You bring a module into your program using the import keyword. Once imported, you access its functions and variables using dot notation — module_name.function_name().
import math # import the built-in math module
# Access functions using dot notation: math.function()
print(math.sqrt(49)) # square root of 49
print(math.pi) # value of pi
print(math.floor(4.9)) # round down
print(math.ceil(4.1)) # round up
print(math.pow(2, 8)) # 2 to the power of 8
3.141592653589793
4
5
256.0
What just happened?
import mathloads the entire math module into your program. You then access everything inside it usingmath.as a prefix.math.sqrt(),math.floor(), andmath.ceil()are functions that would take many lines to write yourself — the module provides them for free.- The dot notation (
math.sqrt) makes it clear exactly where each function comes from — this avoids naming conflicts when you use many modules.
3. Importing Specific Items with from
If you only need one or two things from a module, you can import just those items using from module import item. This lets you use the item directly without the module prefix.
# Import only what you need — no prefix required
from math import sqrt, pi, pow
# Use directly — no "math." prefix needed
print(sqrt(81))
print(pi)
print(pow(3, 4))
# Import everything from a module using *
# (works but not recommended — can cause naming conflicts)
from math import *
print(factorial(5)) # 5! = 120
3.141592653589793
81.0
120
What just happened?
from math import sqrt, pi, powbrings only those three items into your program — you can use them directly withoutmath.in front.from math import *imports everything from the module at once. It is convenient but not recommended because it can accidentally overwrite a variable you already have with the same name.- Best practice: import only what you need. It keeps your code clear and avoids conflicts.
4. Importing with an Alias
You can give a module or imported item a shorter nickname using as. This is especially common with popular data science libraries where typing the full name every time would be tedious. You will see these aliases in almost every professional Python project.
import math as m # "m" is now the alias for math
print(m.sqrt(64))
print(m.pi)
# Alias for a specific item
from math import factorial as fact
print(fact(6)) # 6! = 720
# Real-world example: common aliases used in data science
# import numpy as np ← standard alias for NumPy
# import pandas as pd ← standard alias for Pandas
# These are industry conventions — everyone uses them
3.141592653589793
720
What just happened?
import math as m— you can now typem.sqrt()instead ofmath.sqrt(). Same result, less typing.from math import factorial as fact— the functionfactorialis now available asfactin your code.- Aliases like
npfor NumPy andpdfor Pandas are industry-standard — every data scientist uses them.
5. The math Module — Key Functions
The math module is one of the most commonly used built-in modules. Here is a practical tour of its most useful functions — the ones you will reach for regularly in real programs.
import math
print(math.sqrt(144)) # square root → 12.0
print(math.pow(2, 10)) # 2^10 → 1024.0
print(math.floor(7.8)) # round down → 7
print(math.ceil(7.2)) # round up → 8
print(math.round(7.5)) # standard round → not in math, use built-in
print(round(7.5)) # built-in round
print(math.fabs(-9.5)) # absolute value as float → 9.5
print(math.log(100, 10)) # log base 10 of 100 → 2.0
print(math.pi) # pi constant
print(math.e) # Euler's number
print(math.factorial(7)) # 7! = 5040
1024.0
7
8
8
9.5
2.0
3.141592653589793
2.718281828459045
5040
What just happened?
math.floor()always rounds down andmath.ceil()always rounds up — regardless of the decimal value.math.log(100, 10)calculates the logarithm of 100 in base 10, which equals 2 because 10² = 100.math.piandmath.eare constants — not functions. Access them without parentheses.
6. The random Module
The random module generates random numbers and makes random selections. It is used in games, simulations, testing, security tokens, and anywhere you need unpredictable values.
import random
# Random integer between 1 and 10 (inclusive)
print(random.randint(1, 10))
# Random float between 0.0 and 1.0
print(random.random())
# Random float between two values
print(random.uniform(5.0, 10.0))
# Pick a random item from a list
colors = ["red", "green", "blue", "yellow"]
print(random.choice(colors))
# Pick multiple random items (no repeats)
print(random.sample(colors, 2))
# Shuffle a list in place
cards = [1, 2, 3, 4, 5]
random.shuffle(cards)
print("Shuffled:", cards)
0.6394267984578837
8.233267430648418
blue
['red', 'yellow']
Shuffled: [3, 1, 5, 2, 4]
What just happened?
random.randint(1, 10)returns a random whole number between 1 and 10 — both endpoints included.random.choice(colors)picks one item at random from the list — perfect for games or random assignments.random.sample(colors, 2)picks 2 items without repeating — useful for drawing winners from a list.random.shuffle(cards)rearranges the list in place — the original list is modified directly.- Your output will differ every time you run this — that is the point of random.
7. The datetime Module
The datetime module lets you work with dates and times — getting the current date, formatting dates, calculating time differences, and more. It is used in virtually every real-world application that involves scheduling, logging, or timestamps.
from datetime import datetime, date
# Current date and time
now = datetime.now()
print("Now :", now)
print("Year :", now.year)
print("Month :", now.month)
print("Day :", now.day)
print("Hour :", now.hour)
# Format the date as a readable string
formatted = now.strftime("%B %d, %Y")
print("Formatted :", formatted)
# Today's date only
today = date.today()
print("Today :", today)
# Calculate days between two dates
from datetime import timedelta
deadline = date(2025, 12, 31)
days_left = deadline - today
print("Days until Dec 31, 2025:", days_left.days)
Year : 2025
Month : 3
Day : 1
Hour : 10
Formatted : March 01, 2025
Today : 2025-03-01
Days until Dec 31, 2025: 305
What just happened?
datetime.now()returns the current date and time with full detail — year, month, day, hour, minute, second.strftime()formats a datetime object into a readable string.%B= full month name,%d= day,%Y= 4-digit year.- Subtracting two
dateobjects gives atimedelta— calling.dayson it gives the difference as a plain integer.
8. The os Module
The os module lets your Python program interact with the operating system — reading the current folder, listing files, creating directories, and more. It is essential for any program that works with files and folders.
import os
# Get the current working directory
print("Current folder:", os.getcwd())
# List all files and folders in the current directory
print("Contents:", os.listdir("."))
# Check if a file or folder exists
print("Does 'data.txt' exist?", os.path.exists("data.txt"))
# Join folder and file names safely (works on Windows and Mac/Linux)
path = os.path.join("reports", "sales", "q1.csv")
print("File path:", path)
# Get just the filename from a full path
print("Filename:", os.path.basename(path))
# Get just the folder from a full path
print("Folder :", os.path.dirname(path))
Contents: ['main.py', 'data.txt', 'reports']
Does 'data.txt' exist? True
File path: reports/sales/q1.csv
Filename: q1.csv
Folder : reports/sales
What just happened?
os.getcwd()returns the folder your Python script is currently running from.os.path.join()builds a file path by joining parts with the correct separator for the operating system — use this instead of manually typing slashes to keep your code cross-platform.os.path.exists()checks if a file or folder actually exists before you try to open or delete it — prevents crashes.
9. The sys Module
The sys module gives you access to information about the Python interpreter itself — the version running, the path it searches for modules, and the ability to exit a program. It is used in scripts that need to know their environment.
import sys
# Python version currently running
print("Python version:", sys.version)
# The platform (win32, linux, darwin)
print("Platform:", sys.platform)
# List of folders Python searches when you import a module
print("Module search paths:")
for path in sys.path[:3]: # show first 3 paths only
print(" ", path)
# Exit the program with a status code (0 = success, 1 = error)
# sys.exit(0) ← uncomment this to stop the program here
Platform: linux
Module search paths:
/usr/lib/python311.zip
/usr/lib/python3.11
What just happened?
sys.versionshows which Python version is running — useful when your program needs a minimum version to work correctly.sys.pathis the list of directories Python searches when you writeimport something. If your module is not in one of these folders, Python cannot find it.sys.exit()cleanly stops the program. A status code of0means success; anything else signals an error to the operating system.
10. Creating Your Own Module
Any Python file you create is a module. You can put your helper functions in a separate .py file and import them into any other program. This is how real projects are structured — one file per topic, keeping everything organised.
# --- FILE: mytools.py ---
# Imagine this is saved as mytools.py in the same folder
def greet(name):
return f"Hello, {name}! Welcome to Dataplexa."
def calc_tax(price, rate=8):
"""Returns tax amount. Default rate is 8%."""
return price * rate / 100
def is_even(n):
return n % 2 == 0
TAX_RATE = 8 # a module-level constant
# --- FILE: main.py ---
# Now import from your own module
import mytools
print(mytools.greet("Alex"))
tax = mytools.calc_tax(250)
print(f"Tax on $250: ${tax}")
print("Is 9 even?", mytools.is_even(9))
print("Tax rate :", mytools.TAX_RATE, "%")
Tax on $250: $20.0
Is 9 even? False
Tax rate : 8 %
What just happened?
- Any
.pyfile in the same folder can be imported just like a built-in module — Python finds it automatically. - You can import functions (
greet,calc_tax) and also module-level variables (TAX_RATE) — anything defined at the top level of a module file is importable. - This is the foundation of how large Python projects are organised — instead of one huge file, code is split into focused modules that import from each other.
11. What is a Package?
A package is a folder of Python modules organised together under one name. When a project grows large, you group related modules into folders called packages. A folder becomes a Python package when it contains a special file called __init__.py.
# A package is just a folder with an __init__.py file
# Example folder structure:
#
# myapp/
# ├── __init__.py ← makes this folder a package
# ├── billing.py ← module for billing functions
# ├── users.py ← module for user functions
# └── reports.py ← module for report functions
#
# Importing from a package:
# from myapp import billing
# from myapp.billing import calc_invoice
#
# Real examples of packages you will use later:
import os.path # os is a package, path is a module inside it
print(os.path.join("data", "sales.csv"))
# datetime is also a package
from datetime import datetime
print(datetime.now().year)
2025
What just happened?
os.pathis a real example —osis a package andpathis a module inside it. You have been using a package all along without knowing it.- The
__init__.pyfile can be completely empty — its presence alone tells Python to treat the folder as a package. - As your programs grow, organising code into packages keeps everything clean, navigable, and professional.
12. Installing Third-Party Packages with pip
Python's Standard Library is powerful, but the real magic comes from thousands of free third-party packages created by the Python community. You install them using pip — Python's package installer — from the terminal or command prompt.
# Run these commands in your terminal (not in Python)
# pip install requests ← for making web API calls
# pip install pandas ← for data analysis
# pip install numpy ← for math and arrays
# pip install flask ← for building web apps
# After installing, import them in your Python file like any module:
# import requests
# import pandas as pd
# import numpy as np
# Check what packages are installed
# pip list
# Check the version of a specific package
# pip show requests
# Uninstall a package
# pip uninstall requests
print("pip is run in the terminal, not inside a Python script.")
What just happened?
pip install package_namedownloads and installs the package from the internet into your Python environment.- Once installed, you import third-party packages exactly the same way as built-in modules — Python handles the rest.
pip listshows every package currently installed in your environment — useful for checking what you have available.
13. The if __name__ == "__main__" Guard
When Python runs a file directly, it sets the special variable __name__ to "__main__". When the same file is imported as a module, __name__ is set to the file's name instead. This guard lets you write code that only runs when the file is executed directly — not when it is imported.
def add(a, b):
return a + b
def greet(name):
return f"Hi, {name}!"
# This block ONLY runs when you execute this file directly
# It does NOT run when another file imports this module
if __name__ == "__main__":
print("Running as a standalone script")
print(add(10, 20))
print(greet("Alex"))
30
Hi, Alex!
What just happened?
- When you run this file directly (
python myfile.py),__name__equals"__main__"so the block runs. - When another file does
import myfile,__name__equals"myfile"— the condition is false and the block is skipped. The functions are still available to import. - You will see
if __name__ == "__main__":in almost every professional Python script — it is the standard way to separate reusable code from run-once code.
14. Lesson Summary
| Concept | Syntax / Example | What It Does |
|---|---|---|
| Import module | import math | Loads entire module |
| Import specific item | from math import sqrt | Import one item, no prefix needed |
| Import with alias | import math as m | Use a shorter name for the module |
| math module | math.sqrt(), math.pi | Math functions and constants |
| random module | random.randint(), random.choice() | Generate random values |
| datetime module | datetime.now(), date.today() | Work with dates and times |
| os module | os.getcwd(), os.path.join() | Interact with the file system |
| sys module | sys.version, sys.exit() | Python interpreter info and control |
| Custom module | import mytools | Import your own .py file |
| Package | folder + __init__.py | A folder of related modules |
| Install package | pip install requests | Download and install from PyPI |
| __name__ guard | if __name__ == "__main__": | Runs only when file is executed directly |
🧪 Practice Questions
Answer based on what you learned in this lesson.
1. What keyword is used to load a module into your program?
2. What keyword lets you give a module a shorter nickname when importing it?
3. What tool do you use in the terminal to install third-party Python packages?
4. What file must exist in a folder to make Python treat it as a package?
5. What value does __name__ have when a Python file is run directly?
🎯 Quiz — Test Your Understanding
Q1. Which import lets you use sqrt() directly without a prefix?
Q2. Which function picks one random item from a list?
Q3. Which function builds a file path that works on both Windows and Mac/Linux?
Q4. What happens to the code inside if __name__ == "__main__": when the file is imported by another module?
Q5. Which of these correctly calculates 5! (5 factorial) using the math module?