Academic Block

Python Modules, Import & Packages Get Certified

What Is a Module?

A module is simply a Python file that contains related functions, classes, and variables. Instead of writing every useful tool yourself, you can import modules that other programmers (or the Python standard library) have already written. This keeps your own programs shorter, clearer, and less error-prone. Modules also help you organize large projects by grouping related code into separate files.

Python comes with a rich standard library of modules for mathematics, random numbers, dates and times, statistics, and much more. When you need a capability that is not built into the language itself, the first place to look is usually a standard-library module.

Importing a Whole Module

The simplest way to use a module is to import its entire contents with the import statement. After the import you refer to names inside the module by prefixing them with the module name and a dot. This style makes it obvious where each function comes from and avoids name collisions with your own code.

Most programs begin with a small block of import statements at the top of the file so that a reader can see at a glance which external tools the program relies on.

Try It: Using the math Module

Click Test My Code. Then try a different angle or radius.

What this code does: It imports the entire math module and uses several of its functions to work with a circle and a right triangle.
import math
radius = 5
area = math.pi * radius ** 2
print("Area of circle:", round(area, 2))
print("Square root of 64:", math.sqrt(64))
print("Ceiling of 4.2:", math.ceil(4.2))
print("Floor of 4.8:", math.floor(4.8))

Importing Specific Names with from

When you need only one or two items from a module, you can import them directly with a from ... import statement. Afterward you can use those names without the module prefix. This style is convenient for frequently used functions, but it can make it harder to remember where a name originated if you import many different modules.

A good rule of thumb is to use the plain import module form for most cases and reserve from module import name for the handful of names you use constantly.

Try It: Importing Individual Functions

Click Test My Code. Notice that sqrt and pi can be used without the math. prefix.

What this code does: It imports only the names it needs from the math module and then uses them directly.
from math import sqrt, pi, cos, radians
print("Square root of 144:", sqrt(144))
print("Value of pi:", pi)
angle_degrees = 60
angle_radians = radians(angle_degrees)
print("Cosine of 60°:", round(cos(angle_radians), 3))

Giving a Module an Alias with as

Sometimes a module name is long or you want a shorter nickname for convenience. The as keyword lets you assign an alias to a module (or to an individual name). The most famous example is import numpy as np, but the same technique works with any module.

Aliases keep your code concise while still making the origin of each name clear. Choose short, conventional aliases that other Python programmers will recognize at a glance.

Try It: Module Aliases

Click Test My Code. Then try giving random a different short name.

What this code does: It imports two modules under short aliases and uses them to generate a random score and a square root.
import random as rnd
import math as m
score = rnd.randint(70, 100)
print("Random quiz score:", score)
print("Square root of the score:", round(m.sqrt(score), 2))

Exploring a Module with dir() and help()

When you first encounter a module it is useful to discover what names it contains. The built-in dir() function returns a list of all names defined in a module. For more detailed documentation you can pass a module or a function to help().

These two tools are invaluable while you are learning. They let you explore the standard library interactively without leaving the Python environment.

Try It: Inspecting the statistics Module

Click Test My Code. Scroll through the help text to see the available functions.

What this code does: It imports the statistics module, lists some of its contents, and displays the documentation for the mean function.
import statistics
print("Some names in statistics:")
print([name for name in dir(statistics) if not name.startswith("_")])
print()
help(statistics.mean)

Working with Dates and Times

The datetime module is one of the most frequently used parts of the standard library. It lets you create date and time objects, format them for display, and perform simple arithmetic such as finding the number of days between two dates.

Students often need to work with dates for school projects, sports schedules, or personal calendars. The examples below stay close to everyday situations.

Try It: Today’s Date and a Future Event

Click Test My Code. Then change the target date to a holiday or birthday.

What this code does: It prints today’s date in a American format and calculates how many days remain until the Fourth of July.
from datetime import date, timedelta
today = date.today()
print("Today is", today.strftime("%B %d, %Y"))
july4 = date(today.year, 7, 4)
if july4 < today:
    july4 = date(today.year + 1, 7, 4)
days_left = (july4 - today).days
print("Days until July 4:", days_left)

Generating Random Data

The random module is perfect for simulations, games, and creating sample data for testing. You can draw random integers, choose items from a list, or shuffle a sequence of values. Because the results change each time you run the program, random is also useful for making practice quizzes feel fresh.

Remember that the numbers produced by random are only pseudo-random; they are fine for most student projects but should not be used for cryptographic security.

Try It: Random Student Picker and Dice

Click Test My Code. Run the program several times to see different results.

What this code does: It randomly selects a student from a roster and simulates rolling two six-sided dice.
import random
students = ["Ava", "Liam", "Mia", "Noah", "Emma", "Jackson"]
chosen = random.choice(students)
print("Randomly selected student:", chosen)
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
print("Dice roll:", die1, "and", die2, "→ total", die1 + die2)

Calculating Statistics on Real Data

The statistics module supplies ready-made functions for mean, median, mode, variance, and other common measures. Instead of writing the formulas yourself you can call a well-tested function and focus on the meaning of the results.

These tools are especially handy for science-fair projects, sports statistics, or analyzing quiz scores from an university classroom.

Try It: Class Quiz Statistics

Click Test My Code. Then add or remove a few scores and observe how the statistics change.

What this code does: It computes the mean, median, and standard deviation of a list of quiz scores.
import statistics
scores = [88, 92, 75, 96, 81, 90, 67, 85]
print("Scores:", scores)
print("Mean:  ", round(statistics.mean(scores), 1))
print("Median:", statistics.median(scores))
print("Stdev: ", round(statistics.stdev(scores), 1))

Putting Modules Together – A Small Weather Helper

Real programs often import several modules and combine their capabilities. The example below uses random to invent a plausible temperature and statistics to summarize a short series of readings. This pattern—import what you need, then orchestrate the pieces—is the everyday style of Python programming.

As your projects grow you will also start creating your own modules by saving related functions in separate .py files and importing them the same way you import the standard library.

Try It: Simulated Weekly Temperatures

Click Test My Code. Run it a few times to see different weekly patterns.

What this code does: It generates seven random high temperatures for a Midwestern city and then reports the weekly average and the warmest day.
import random
import statistics
temps = [random.randint(55, 85) for _ in range(7)]
print("Daily highs (°F):", temps)
print("Weekly average:", round(statistics.mean(temps), 1))
print("Warmest day:", max(temps))
print("Coolest day:", min(temps))
Tip: Keep import statements at the top of your file and group them logically—standard-library modules first, then third-party packages, then your own local modules. This conventional order makes programs easier for other people to read.

What Is a Package?

A package is a way of organizing related modules into a folder hierarchy. While a module is a single .py file, a package is a directory that contains multiple modules (and possibly sub-packages). This structure helps keep large projects tidy and prevents name collisions when many files are involved.

Python recognizes a directory as a package when it contains a special file named __init__.py. This file can be empty, or it can contain initialization code that runs when the package is imported. Once the folder has an __init__.py, you can import modules from it using dotted names such as mypackage.utils or mypackage.helpers.math_tools.

In everyday student projects you may not need packages right away, but understanding them is important because almost every third-party library you will later install (NumPy, pandas, matplotlib, etc.) is distributed as a package.

Try It: Conceptual Package Structure

The example below shows how a simple package might be organized and how you would import from it. (This is illustrative — the browser environment cannot create real folders, but the import syntax is exactly what you would use on your own computer.)

What this code illustrates: A small school-project package that contains two modules, and the different ways you can import from it.
# Imaginary folder structure:
# school_tools/
#     __init__.py
#     grades.py
#     attendance.py

# Inside grades.py you might have:
def average(scores):
    return sum(scores) / len(scores)

# Inside attendance.py you might have:
def days_present(present, total):
    return round(present / total * 100, 1)

# How you would import and use the package:
# import school_tools.grades
# print(school_tools.grades.average([88, 92, 95]))

# or the more common form:
# from school_tools.grades import average
# from school_tools.attendance import days_present
# print(average([88, 92, 95]))
# print(days_present(17, 20))

print("Package concept demonstrated (see comments above).")
print("On your own computer you would create the folders and .py files.")

Common Mistakes with Modules and import

  • Forgetting to import: Using a name such as sqrt without first importing it (or the module that contains it) raises a NameError.
  • Circular imports: Two of your own modules that import each other can cause confusing errors; redesign the code so that the dependency goes only one way.
  • Importing inside a function unnecessarily: Imports are usually placed at the top level so they run only once. Importing inside a function is appropriate only when you want to delay a heavy import or avoid a circular dependency.
  • Using from module import * : The star import brings every public name into the current namespace and makes it hard to see where names come from. Prefer explicit imports.
  • Misspelling the module name: import maths (with an extra s) fails because the standard module is called math.
  • Assuming a module is already loaded: Each program starts with a clean slate; every module you need must be imported in that program.

Good Habits for Using Modules

  • Place all import statements near the top of the file.
  • Prefer import module for most cases; use from module import name only for the few names you call constantly.
  • Choose clear, conventional aliases (np for numpy, pd for pandas, plt for matplotlib.pyplot).
  • Explore unfamiliar modules with dir() and help() before writing production code.
  • When you write your own modules, give them short, descriptive names and keep related functions together.
  • Document any non-obvious third-party dependencies so other students or collaborators can install them.

Key Takeaways

  • A module is a file of related Python code that can be imported and reused.
  • import module brings the whole module in under its own name.
  • from module import name brings selected names directly into your namespace.
  • as lets you give a module or a name a shorter alias.
  • dir() and help() are the interactive tools for exploring any module.
  • The standard library already contains modules for math, random numbers, dates, statistics, and many other common needs.
  • Well-organized imports and clear module boundaries make larger programs easier to maintain.

Frequently Asked Questions

What is the difference between a module and a package?

A module is a single Python file. A package is a directory that contains multiple modules together with a special __init__.py file. Packages let you organize larger libraries into a hierarchy of sub-modules.

When should I use import module versus from module import name?

Use import module when you want the origin of every name to be obvious. Use from module import name when a few names are used so frequently that the repeated module prefix would become noisy.

What does import module as alias do?

It loads the module and binds it to the name you choose as the alias. Afterward you write alias.function instead of module.function. This is useful for long module names or for following community conventions such as import numpy as np.

How can I see everything a module contains?

Call dir(module) to obtain a list of names. For detailed documentation on a specific function call help(module.function) or help(module).

Why do some people write from module import * ?

The star import brings every public name from the module into the current namespace. It is convenient for quick interactive experiments but is discouraged in real programs because it pollutes the namespace and hides the origin of names.

Can I create my own modules?

Yes. Any .py file can be imported as a module provided it is on the Python search path. Simply save your functions in a file such as helpers.py and then write import helpers or from helpers import my_function.

What is the standard library?

The standard library is the large collection of modules that ship with every official Python installation. It includes math, random, datetime, statistics, json, re, and dozens of other useful tools. You do not need to install anything extra to use them.

Does the order of import statements matter?

Python executes imports in the order they appear, but the conventional style is to group them: standard-library modules first, then third-party packages, then local application modules. Within each group the names are usually sorted alphabetically.

Ready for the next step?Learn how to create isolated environments and manage third-party packages with pip and venv.
Next: Packages & Environments →