Skip to content
Kuza Ndoto Academy

Importing Modules

Beginner → IntermediateChapter 6 · Page 31 of 565 min readUpdated 15 Nov 2026

A module is simply a file of Python code that other programs can reuse. The import statement lets you borrow tools from modules, so you can calculate square roots, pick random winners or download web pages without writing that code yourself.

What is a module?

Every .py file is a module. When a file contains useful functions, variables or classes, another program can import it and use them. Modules come from three places:

SourceExamplesHow you get it
The standard librarymath, random, datetime, jsonAlready installed with Python
Third-party packagesrequests, pandas, djangoInstalled with pip
Your own fileshelpers.py, mpesa_utils.pyFiles you write in your project

Splitting code into modules keeps programs organised. Instead of one enormous file, you group related tools together and import them wherever they are needed.

The import statement

The simplest form is import module_name. You then reach the module's contents with dot notation: module.name.

import math

print(math.sqrt(144))     # square root
print(math.pi)            # a constant stored in the module
print(math.ceil(4.2))     # round up
print(math.floor(4.8))    # round down
12.0 3.141592653589793 5 4

The module name acts like a label on a box. Writing math.sqrt makes it clear where sqrt came from, and it stops names from different modules clashing. This "box of names" is called the module's namespace.

Importing specific names with from

If you only need one or two things, use from module import name. The names are copied into your program, so you use them without the module prefix.

from math import sqrt, pi

radius = 3
area = pi * radius ** 2
print(round(area, 2))
print(sqrt(81))
28.27 9.0

This is shorter to type, but a reader has to scroll up to see where sqrt came from. Both styles are fine; choose the one that keeps your code clearest.

math module sqrt pi ceil floor import math your namespace gets one name: math use math.sqrt(144) from math import sqrt, pi your namespace gets the names themselves: sqrt pi use sqrt(81)
Figure 1. import math adds one name (the module) to your program; from math import ... copies the chosen names in directly, so you drop the prefix.

Giving a module a nickname with as

The as keyword gives a module (or a name) a shorter alias. Some aliases are so common that every Python developer recognises them, such as import numpy as np and import pandas as pd.

import statistics as stats
from datetime import date as Date

marks = [62, 75, 88, 91, 70]
print(stats.median(marks))
print(stats.mode(["M-Pesa", "Cash", "M-Pesa", "Card"]))
print(Date(2026, 3, 14))
75 M-Pesa 2026-03-14
Common mistake

Avoid from module import *. It dumps every public name from the module into your program, so you can't tell where a name came from, and it can silently replace names you already have. For example, the os module has its own open() function, and from os import * hides the built-in open() you normally use for files.

Exploring what a module contains

Use dir() to list the names inside a module and help() to read its built-in documentation. Both work in the interactive shell, which makes them handy for exploring.

import math

log_functions = [name for name in dir(math) if name.startswith("log")]
print(log_functions)
['log', 'log10', 'log1p', 'log2']

The random module is a favourite for games and simulations. Because it produces random values, your results will differ from the example below.

import random

print(random.randint(1, 6))                              # roll a die
print(random.choice(["Nairobi", "Kisumu", "Mombasa"]))   # pick one item
4 Kisumu

How Python finds a module

When you write import something, Python looks in this order:

  1. The folder containing the script you are running.
  2. Any folders listed in the PYTHONPATH environment variable (if set).
  3. The standard library.
  4. The site-packages folder, where pip installs third-party packages.

The full list is stored in sys.path. Python loads each module only once per program run and caches it, so importing the same module in ten places doesn't run its code ten times.

If Python can't find the module anywhere, you get a ModuleNotFoundError. This usually means you misspelt the name or haven't installed the package yet.

import requests
Traceback (most recent call last): File "app.py", line 1, in <module> import requests ModuleNotFoundError: No module named 'requests'

The fix is to install it inside your project's virtual environment, which is covered in pip & virtual environments.

Common mistake

Never name your own file after a module you want to import. If you save a script as random.py and then write import random, Python finds your file first (it's in the script's folder) and you get confusing errors such as "module 'random' has no attribute 'randint'". Rename your file to something like dice_game.py and delete any __pycache__ folder next to it.

Import style tips

  • Put all imports at the top of the file, one module per line.
  • Group them: standard library first, then third-party packages, then your own modules, with a blank line between groups.
  • Prefer import module or from module import name over star imports.
import json
import math

import requests

from budget import add_expense

Key points

  • A module is a .py file of reusable code; import it to use its tools.
  • import math keeps the prefix (math.sqrt); from math import sqrt drops it.
  • as creates an alias, such as import pandas as pd.
  • ModuleNotFoundError means a typo or a package that isn't installed.
  • Don't name your files after modules you import. Next, take a tour of the standard library.
Up next · Modules & PackagesThe Standard LibraryA tour of Python's built-in toolbox.
→

Tip: use the ← and → keys to move between pages.