🐍 Python for Everyone

← Back to all chapters

Chapter 11 of 27 Intermediate 40 min read

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

Nobody at a real company writes their own square root function, their own calendar math, or their own random number generator from scratch. Someone already solved those problems carefully, tested them for years, and packaged the result into Python itself. 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.
Sub-topic 1 of 6

1. What is a module, and why organize code this way

At a glance
  • A module is nothing exotic — it's just a .py file containing reusable code.
  • Python ships with a huge collection of ready-made modules called the standard library.
  • import lets one file use the functions and values defined in another file — yours or Python's own.
Why this matters: every function you've written since Chapter 10 has lived in one file. Real programs eventually outgrow that — modules are how code gets organized across many files instead of one giant script.
What is... a module? A module is simply a file ending in .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:

first_import.py
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.

What is... the standard library? The standard library is the large collection of modules that comes bundled with Python itself — 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:

helpers.py
def shout(text):
    return text.upper() + "!"
main.py — in the same folder as helpers.py
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.

try_first_import.py
Click "Run Code" — try importing math and using a different number.
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.

Quick recap
  • A module is just a .py file 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.
Sub-topic 2 of 6

2. Import variations

At a glance
  • import x brings in the whole module; use x.name to reach anything inside it.
  • from x import y brings in just one name, usable directly without the module prefix.
  • as renames whatever's being imported — a module or a specific name.
Use this when: you know exactly which import style fits — the four variations below cover nearly every import you'll ever write.

All four variations import the exact same sqrt function from math — they just differ in what name you end up calling it by:

import_variations.py
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
actual output of import_variations.py — every line computes the same value
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.

What is... 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.

avoid_star_import.py
# 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
try_import_variations.py
Click "Run Code" — try renaming power back to pow with as.
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.

Quick recap
  • import x brings in the whole module, accessed as x.name.
  • from x import y brings in just y, usable directly with no prefix.
  • as renames an import; avoid from x import * since it hides where names came from and can silently overwrite existing ones.
Sub-topic 3 of 6

3. The math module

At a glance
  • math.sqrt(x) returns the square root of x as a float.
  • math.floor(x) rounds down, math.ceil(x) rounds up — both to the nearest whole number.
  • math.pow(x, y) raises x to the power y; math.pi is the constant π, ready to use.
Use this when: a calculation needs more than + - * / and ** already cover — square roots, rounding in a specific direction, or geometry involving π.
What is... the 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:

shipping_weight.py
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:

floor_ceil_pow_sqrt.py
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
actual output of floor_ceil_pow_sqrt.py
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.

What is... 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:

circle_area.py
import math

def circle_area(radius):
    return math.pi * radius ** 2

print(round(circle_area(5), 2))   # 78.54
try_math_module.py
Click "Run Code" — try computing math.pow(5, 3).
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.

Quick recap
  • math.sqrt(x) returns the square root of x as a float.
  • math.floor(x) rounds down, math.ceil(x) rounds up.
  • math.pow(x, y) raises x to the power y; math.pi is the constant π.
Sub-topic 4 of 6

4. The datetime module

At a glance
  • datetime.date.today() and datetime.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 .days attribute is the number of days between them.
Use this when: a program needs to know today's date, display a date in a specific format, or calculate how far apart two dates are.
What is... the 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:

todays_date.py
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:

specific_date.py
import datetime

launch_day = datetime.date(2026, 3, 15)
print(launch_day)   # 2026-03-15
What is... 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:

strftime_formatting.py
import datetime

launch_day = datetime.date(2026, 3, 15)
print(launch_day.strftime("%B %d, %Y"))   # March 15, 2026
actual output of strftime_formatting.py
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:

date_difference.py
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)
actual output of date_difference.py
Today: 2026-07-05
Birthday: 2026-12-25
Days left: 173
What is... a 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.
try_datetime_module.py
Click "Run Code" — try changing start and end to two dates of your own.
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).

Quick recap
  • 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 .days attribute is the number of days between them.
Sub-topic 5 of 6

5. The random module

At a glance
  • random.randint(a, b) returns a random whole number between a and b, 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.
Use this when: a program needs unpredictability on purpose — a dice roll, a shuffled deck, picking a random winner from a list of entries.
What is... the 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:

dice_roller.py
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:

random_choice.py
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
What is... 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:

shuffle_deck.py
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:

try_random_module.py
Click "Run Code" a few times — the numbers and topping change each run.
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.

Quick recap
  • random.randint(a, b) returns a random whole number from a to b, inclusive.
  • random.choice(sequence) picks one random item from a list.
  • random.shuffle(list) randomly reorders a list in place, returning None.
Sub-topic 6 of 6

6. Real-world use of modules in production

At a glance
  • 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.
Pattern to remember: reach for the standard library before writing something from scratch — there's a good chance the problem is already solved, tested, and one 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:

order_confirmation.py
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))
actual output of order_confirmation.py
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.

What is... a package? A package is a folder containing multiple related modules, plus a special file named __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.

try_bringing_together.py
Click "Run Code" — try changing the number of sides on the die.
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.

Quick recap
  • 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__.py file — a bigger-scale organization tool than a single module.
  • Real Python projects also install modules written by other people, using the same import keyword this chapter introduced.
In the Real World

Points to Remember

← All Chapters Take the Quiz →