Skip to content
Laviyx Learn

Try

Python course menu

Python Modules: import, from ... import, and Creating Your Own

Learn Python modules: import the standard library (math, random, statistics), use from-import and aliases, create your own module, understand if __name__ == '__main__', and fix ModuleNotFoundError.

Intermediate7 min readUpdated
On this page

A module is simply a Python file that contains code (functions, variables, classes) you can reuse in other files. Python ships with hundreds of ready-made modules, called the standard library, and you can write your own to keep large programs organised.

Importing a module#

Python
import math

print(math.sqrt(16), math.pi, math.ceil(4.2), math.floor(4.8))
Output
4.0 3.141592653589793 5 4

import math loads the module once; you then use its contents with dot notation: math.sqrt, math.pi.

Importing specific names#

from ... import ... brings names directly into your file, so you can drop the prefix:

Python
from math import sqrt, pi

print(sqrt(25), round(pi, 3))
Output
5.0 3.142

You can also give a module a shorter alias:

Python
import datetime as dt
print(type(dt.date(2026, 10, 23)).__name__)
Output
date
StyleUse it when…
import mathyou use several things from the module; the prefix shows where each comes from
from math import sqrtyou use one or two names often
import numpy as npthe module name is long and a common alias exists

A tour of useful standard modules#

Python
import random

random.seed(42)   # makes the "random" results repeatable
print(random.randint(1, 6), random.choice(["red", "green", "blue"]))

nums = [1, 2, 3, 4, 5]
random.shuffle(nums)
print(nums)
Output
6 red
[2, 4, 5, 3, 1]

Without random.seed(42), you would get different values each run, which is usually what you want. Seeding is useful for tests and for reproducing results.

Python
import statistics

data = [70, 85, 85, 90, 100]
print(statistics.mean(data), statistics.median(data), statistics.mode(data))
Output
86 85 85

Other modules you will use often:

ModuleFor
mathsquare roots, rounding up/down, constants
randomrandom numbers and choices
statisticsmean, median, standard deviation
datetimedates and times (lesson)
jsonreading and writing JSON (lesson)
pathlib, osfiles and folders (lesson)
reregular expressions (lesson)
csvCSV files
collectionsCounter, defaultdict, deque

To see what a module contains, use dir() or help():

Python
import math
print(dir(math)[:8])
Output
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin']

Creating your own module#

Any .py file is a module. Create helpers.py:

helpers.py (Python)
"""Small helper functions."""

TAX_RATE = 0.18

def add_tax(price):
    return round(price * (1 + TAX_RATE), 2)

def greet(name):
    return f"Hello, {name}!"

In another file in the same folder:

main.py (Python)
import helpers

print(helpers.add_tax(100))
print(helpers.greet("Asha"))
print(helpers.TAX_RATE)

from helpers import greet
print(greet("Ravi"))
Output
118.0
Hello, Asha!
0.18
Hello, Ravi!

The module name is the file name without .py.

if name == "main"#

When Python runs a file directly, it sets the special variable __name__ to "__main__". When the file is imported, __name__ is the module's name instead. This lets a file contain code that runs only when executed directly:

tools.py (Python)
def double(n):
    return n * 2

if __name__ == "__main__":
    print("Running tools.py directly")
    print(double(21))

Running python tools.py prints both lines. But importing it from another file:

Python
import tools
print("imported, double(5) =", tools.double(5))
Output
imported, double(5) = 10

The test code inside the if did not run. This pattern lets a module be both a reusable library and a runnable script.

When an import fails#

Python
import nonexistent_module
Output
ModuleNotFoundError: No module named 'nonexistent_module'

Usual causes:

  1. A typo in the name.
  2. A third-party package that is not installed yet: install it with python -m pip install name (see Packages).
  3. Your own module is in a different folder from the file importing it.
  4. You named your own file the same as a module, such as random.py, which hides the real one.

Common mistakes#

Practice#

Practice exercise

Using the math module, write a program that prints the area of a circle with radius 7, rounded to 2 decimal places, and the radius rounded up to the nearest whole number after dividing it by 2.

Show hint

Area is math.pi * r ** 2; rounding up is math.ceil().

Show solution
Python
import math

r = 7
print(round(math.pi * r ** 2, 2))
print(math.ceil(r / 2))
Output
153.94
4

Key takeaway#

Finished this lesson?