Modules & Packages
Every program up to this point has lived in a single file, using only the tools Python gives you automatically. That's about to change. Python ships with a huge standard library of ready-made code — for math, dates, randomness, and much more — and this chapter opens the door to it with import. You'll also see why organizing your own code across multiple files matters as programs grow, and pick up three genuinely useful modules along the way: math, datetime, and random.
How to read this chapter
importis finally allowed — but only for the three modules this chapter teaches:math,datetime, andrandom. They're all safe, don't touch the filesystem, and don't need error handling (that's Chapter 12).- Sub-topics 3-5 are hands-on tours of one module each — read them in order, or jump straight to whichever module you need right now.
- This is where "the standard library" stops being an abstract phrase. Real production code leans on it constantly, and this chapter is the first taste of why.
import is the single word that unlocks all of it — instead of reinventing a wheel, you borrow one that millions of other programs already rely on.
1. What is a module, and why organize code this way
- A module is nothing exotic — it's just a
.pyfile containing reusable code. - Python ships with a huge collection of ready-made modules called the standard library.
importlets one file use the functions and values defined in another file — yours or Python's own.
.py that contains
Python code — functions, variables, anything. The moment you
import that file by name (without the .py),
you can use whatever it defines. There's no special ceremony to
"make" a module; any Python file already qualifies as one.
Python comes with hundreds of modules built in — this is called the standard library, and it's already installed wherever Python runs. No downloading, no setup:
import math
print(math.sqrt(16)) # 4.0 — sqrt() lives inside the math module
import math loads the entire math module
and makes it available under the name math. Writing
math.sqrt(16) — module name, a dot, then the function —
is how you reach inside a module to use something it defines.
math, datetime,
and random (this chapter's three) are just a tiny slice
of it. It exists so nobody has to rewrite well-tested, common
functionality from scratch.
Importing your own files works the exact same way, once you have
more than one .py file in a project. A small
helpers.py file full of functions can be imported into
a main script exactly like math can:
def shout(text):
return text.upper() + "!"
import helpers
print(helpers.shout("hello")) # HELLO!
As a program grows from ten lines to a thousand, keeping every function in one file becomes hard to navigate and hard to test. Splitting related functions into their own files — one for validation logic, one for calculations, one for formatting — is exactly how real, production-scale Python projects stay manageable, even with dozens of contributors working on different pieces at once.
Go Deeper: import only runs once per program
No matter how many times import math appears across a
program's files, Python only actually loads and runs the module
once — every later import math just reuses what's
already loaded. This is why importing the same module in several
files of a larger project is completely normal and has no real
performance cost.
- A module is just a
.pyfile of reusable code — nothing more. - The standard library is the large set of modules Python ships with automatically.
- Splitting code across multiple files/modules is how real, larger programs stay organized and maintainable.
2. Import variations
import xbrings in the whole module; usex.nameto reach anything inside it.from x import ybrings in just one name, usable directly without the module prefix.asrenames whatever's being imported — a module or a specific name.
All four variations import the exact same sqrt
function from math — they just differ in what name you
end up calling it by:
import math
print(math.sqrt(2)) # 1.4142135623730951 — full module, dotted access
from math import sqrt
print(sqrt(2)) # 1.4142135623730951 — just sqrt, no prefix needed
from math import sqrt as square_root
print(square_root(2)) # 1.4142135623730951 — sqrt, renamed on the way in
import math as m
print(m.sqrt(2)) # 1.4142135623730951 — whole module, renamed to m
1.4142135623730951
1.4142135623730951
1.4142135623730951
1.4142135623730951
import x is the safest default — math.sqrt
makes it obvious, everywhere it's used, exactly which module a
function came from. from x import y trades that clarity
for shorter code, which is worth it when a name is used constantly
throughout a file.
as?
as gives an import a different local name. import
math as m still imports the whole math module —
it's just now called m in this file. It's most useful
for shortening a long module name, or avoiding a clash with another
name already in use.
One variation is worth knowing about specifically so it can be
avoided: from math import * imports everything
from a module at once, with no prefix at all.
- It's unclear later which function came from which module, once several
import *lines are used in the same file. - It can silently overwrite an existing name in your file with something from the module, without any warning.
- Nearly every real Python style guide, including Python's own official one (PEP 8), recommends against it.
# Avoid this:
from math import *
print(sqrt(2)) # works, but where did sqrt come from? unclear at a glance
# Prefer this instead:
from math import sqrt
print(sqrt(2)) # clearly imported from math, right above
Go Deeper: importing multiple names at once
from math import sqrt, floor, ceil imports several
specific names from the same module in a single line, comma
separated — each one usable directly, without a module prefix.
This is a common middle ground: more explicit than
import *, less repetitive than a separate
from math import line for every single name.
import xbrings in the whole module, accessed asx.name.from x import ybrings in justy, usable directly with no prefix.asrenames an import; avoidfrom x import *since it hides where names came from and can silently overwrite existing ones.
3. The math module
math.sqrt(x)returns the square root ofxas a float.math.floor(x)rounds down,math.ceil(x)rounds up — both to the nearest whole number.math.pow(x, y)raisesxto the powery;math.piis the constant π, ready to use.
+ - * / and ** already cover — square roots, rounding in a specific direction, or geometry involving π.
math module?
math is a standard-library module of common
mathematical functions and constants — square roots, rounding,
powers, trigonometry, and more — that go beyond Python's built-in
arithmetic operators.
A shipping calculator needs to round a package's weight up to the
next whole pound before charging — rounding down would undercharge,
so math.ceil is exactly the right tool:
import math
actual_weight = 3.2
billable_weight = math.ceil(actual_weight)
print(billable_weight) # 4 — always rounds up, never in the customer's favor
math.floor is ceil's opposite — it always
rounds down, which fits a situation like figuring out how many
complete boxes of 12 eggs you can fill from a given count:
import math
print(math.floor(4.7)) # 4 — rounds down
print(math.ceil(4.2)) # 5 — rounds up
print(math.pow(2, 10)) # 1024.0 — 2 to the power of 10, always a float
print(math.sqrt(16)) # 4.0 — square root, always a float
4
5
1024.0
4.0
math.pow(x, y) and Python's own **
operator (from Chapter 2) compute the same thing — 2 **
10 and math.pow(2, 10) both give 1024.
The difference is small but worth knowing: ** keeps a
whole-number result as an int, while
math.pow always returns a float.
math.pi?
math.pi isn't a function — it's a constant, the value
of π (about 3.14159...) stored directly in the
module. No parentheses needed; just math.pi on its own.
A circle's area formula, πr², is a natural place to use
math.pi directly instead of typing out digits by hand:
import math
def circle_area(radius):
return math.pi * radius ** 2
print(round(circle_area(5), 2)) # 78.54
Go Deeper: math.sqrt vs. ** 0.5
16 ** 0.5 and math.sqrt(16) both give
4.0 — Python doesn't strictly require the
math module for square roots. math.sqrt
is still the clearer, more readable choice for this specific job,
and it also raises a clear error for negative numbers rather than
returning a confusing complex number, which is why real code
reaches for it by name instead of the ** 0.5 trick.
math.sqrt(x)returns the square root ofxas a float.math.floor(x)rounds down,math.ceil(x)rounds up.math.pow(x, y)raisesxto the powery;math.piis the constant π.
4. The datetime module
datetime.date.today()anddatetime.datetime.now()give the current date, or date-and-time.strftime()formats a date/time into a specific, readable string layout.- Subtracting one date from another gives a
timedelta, whose.daysattribute is the number of days between them.
datetime module?
datetime is a standard-library module for working with
dates and times — creating them, formatting them for display, and
doing arithmetic like "how many days between these two dates."
datetime.date.today() returns today's date, read
straight from the computer's clock — your own output will show
whatever today's actual date is when you run it:
import datetime
today = datetime.date.today()
print(today) # your output will show today's actual date, e.g. 2026-07-05
For anything that needs a specific, known date instead of "right
now" — like the examples below, so the output here matches exactly
what you'll see — datetime.date(year, month, day)
builds one directly:
import datetime
launch_day = datetime.date(2026, 3, 15)
print(launch_day) # 2026-03-15
strftime?
strftime ("string format time") converts a date or
datetime object into a string, laid out exactly however you
specify — %B for the full month name, %d
for the day, %Y for a four-digit year, and more.
Raw dates print in a plain YYYY-MM-DD shape by default
— fine for a computer, awkward for a human-facing message.
strftime reformats it into something more readable:
import datetime
launch_day = datetime.date(2026, 3, 15)
print(launch_day.strftime("%B %d, %Y")) # March 15, 2026
March 15, 2026
Subtracting one date from another is where datetime
earns its keep in real programs — a countdown page, a subscription
renewal reminder, or an age calculator all boil down to this same
pattern:
import datetime
today = datetime.date(2026, 7, 5)
birthday = datetime.date(2026, 12, 25)
days_left = birthday - today
print("Today:", today)
print("Birthday:", birthday)
print("Days left:", days_left.days)
Today: 2026-07-05
Birthday: 2026-12-25
Days left: 173
timedelta?
A timedelta is the result of subtracting one date (or
datetime) from another — it represents a span of time, not a point
in time. Its .days attribute gives that span as a plain
whole number of days, which is usually exactly what you want out of
it.
Go Deeper: date vs. datetime
datetime.date stores just a year, month, and day —
no time of day at all. datetime.datetime stores all
of that plus hours, minutes, and seconds, and its
datetime.datetime.now() gives the exact current
moment. Use date when only the calendar day matters
(a birthday, a deadline); use datetime when the time
of day matters too (a log entry, an appointment).
datetime.date.today()gives today's date;datetime.date(y, m, d)builds a specific one.strftime("%B %d, %Y")-style format strings turn a date into a readable string.- Subtracting two dates gives a
timedelta; its.daysattribute is the number of days between them.
5. The random module
random.randint(a, b)returns a random whole number betweenaandb, both included.random.choice(sequence)picks one random item out of a list (or any sequence).random.shuffle(list)rearranges a list's items into a random order, in place.
random module?
random is a standard-library module for generating
randomness — random numbers, random choices from a list, and
randomly reordering a list — used anywhere a program needs an
outcome that isn't fixed in advance.
A dice roller is the simplest possible use of random:
randint(1, 6) mirrors an actual six-sided die exactly,
since both 1 and 6 are valid results:
import random
roll = random.randint(1, 6)
print("You rolled:", roll) # a random whole number from 1 to 6, inclusive
Because the result is genuinely random, your own output will show a
different number practically every time you run it — that's the
whole point. random.choice works the same way, but
picks a random item out of an existing list instead of a number:
import random
players = ["Priya", "Amir", "Zoe", "Sam"]
first_turn = random.choice(players)
print(first_turn, "goes first!") # a random name from the list, different each run
random.shuffle?
random.shuffle(some_list) rearranges a list's items
into a random order, directly modifying that list in place — it
doesn't return a new shuffled list, it changes the original one and
returns None.
Shuffling a deck of cards (or any list of items) before dealing is a
classic use — this is also a good moment to remember that
shuffle changes the list itself, so printing it
afterward is what shows the new order:
import random
cards = ["Ace", "King", "Queen", "Jack", "10"]
random.shuffle(cards)
print(cards) # the same 5 cards, in a new random order each run
Because every example on this page uses genuine randomness, running the playground below more than once will very likely give a different result each time — that's expected, not a bug:
Go Deeper: random.seed() makes randomness repeatable
random.seed(some_number), called once before any
other random function, makes every "random" result
after it fully predictable and repeatable — the same seed always
produces the same sequence of "random" results. This is genuinely
useful for testing code that depends on random, since
a test needs a predictable expected answer to check against. It's
mentioned here just so the name isn't a surprise later; everyday
use of random doesn't need it.
random.randint(a, b)returns a random whole number fromatob, inclusive.random.choice(sequence)picks one random item from a list.random.shuffle(list)randomly reorders a list in place, returningNone.
6. Real-world use of modules in production
- The standard library exists so common problems only need solving once, by Python's own maintainers, instead of by every programmer separately.
- Real projects also install modules written by other people — that's a step beyond this course, but worth knowing exists.
- A package is a folder of related modules, bundled together — a natural next step once a project outgrows a handful of loose files.
import away.
A simple order-confirmation message can combine everything this
chapter covered — math for a rounded total,
datetime for a delivery estimate, and it's exactly the
kind of small utility real order-processing systems run thousands of
times a day:
import math
import datetime
def build_confirmation(item, price, order_date):
rounded_price = math.ceil(price)
delivery_date = order_date + datetime.timedelta(days=5)
return (
item
+ " confirmed at $"
+ str(rounded_price)
+ " — arriving by "
+ delivery_date.strftime("%B %d, %Y")
)
order_date = datetime.date(2026, 7, 5)
print(build_confirmation("Desk Lamp", 24.10, order_date))
Desk Lamp confirmed at $25 — arriving by July 10, 2026
Every standard-library module exists for the same reason: someone already solved "how do I work with dates" or "how do I generate randomness" carefully, handled the tricky edge cases, and shipped it with Python so nobody else has to solve it again from scratch.
__init__.py that tells Python "this
folder is a package, not just an ordinary folder." Real projects
often group dozens of modules into packages once they outgrow a
handful of loose files — that's a larger-scale organization tool
than this course covers yet, but the name is worth recognizing when
you see it later.
This chapter deliberately stuck to three safe, simple modules. The
standard library has hundreds more — os for working
with files and folders, json for structured data,
sys for interacting with the running program itself —
each one unlocked by the exact same import keyword
learned here, once later chapters cover what they need
(exception handling, file I/O) to use them safely.
Go Deeper: modules other people wrote (a preview)
Beyond Python's own standard library, the wider Python community
publishes tens of thousands of additional packages — for web
development, data analysis, machine learning, and nearly anything
else — installed with a tool called pip rather than
being built in. That's beyond this course's current scope, but
it's the same import keyword doing the work once a
package is installed, which is exactly why this chapter's habit of
reaching for the standard library first pays off later.
- The standard library exists so common problems are solved once, well, instead of by every programmer separately.
- A package is a folder of related modules with an
__init__.pyfile — a bigger-scale organization tool than a single module. - Real Python projects also install modules written by other people, using the same
importkeyword this chapter introduced.
- Nearly every production Python program starts with a block of
importstatements — pulling in the standard library and other packages before a single line of the program's own logic runs. - Date math like Sub-topic 4's
timedeltapattern powers subscription renewal emails, "your order arrives by" estimates, and expiration warnings across countless real applications. - Randomness from Sub-topic 5 shows up far beyond games — A/B testing which version of a webpage a visitor sees, shuffling a quiz's question order, or randomly sampling data for testing all lean on the same
randommodule.
Points to Remember
- A module is just a
.pyfile of reusable code; the standard library is the huge collection of modules Python ships with automatically. import xbrings in a whole module (accessed asx.name);from x import ybrings in one name directly;asrenames either — but avoidfrom x import *, since it hides where names came from.- The
mathmodule covers calculations beyond basic arithmetic:sqrt,floor,ceil,pow, and the constantpi. - The
datetimemodule creates and formats dates (date.today(),strftime) and computes the gap between two dates as atimedelta. - The
randommodule generates unpredictability on purpose:randintfor a random number,choicefor a random pick,shuffleto reorder a list in place. - This chapter's
importis limited tomath,datetime, andrandom— safe modules that don't need file I/O or exception handling, both covered in later chapters. - A package is a folder of related modules with an
__init__.pyfile — a larger-scale organization tool worth recognizing, even though building one is beyond this course so far.