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.
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#
import math
print(math.sqrt(16), math.pi, math.ceil(4.2), math.floor(4.8))4.0 3.141592653589793 5 4import 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:
from math import sqrt, pi
print(sqrt(25), round(pi, 3))5.0 3.142You can also give a module a shorter alias:
import datetime as dt
print(type(dt.date(2026, 10, 23)).__name__)dateA tour of useful standard modules#
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)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.
import statistics
data = [70, 85, 85, 90, 100]
print(statistics.mean(data), statistics.median(data), statistics.mode(data))86 85 85Other modules you will use often:
To see what a module contains, use dir() or help():
import math
print(dir(math)[:8])['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin']Creating your own module#
Any .py file is a module. Create helpers.py:
"""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:
import helpers
print(helpers.add_tax(100))
print(helpers.greet("Asha"))
print(helpers.TAX_RATE)
from helpers import greet
print(greet("Ravi"))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:
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:
import tools
print("imported, double(5) =", tools.double(5))imported, double(5) = 10The 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#
import nonexistent_moduleModuleNotFoundError: No module named 'nonexistent_module'Usual causes:
- A typo in the name.
- A third-party package that is not installed yet: install it with
python -m pip install name(see Packages). - Your own module is in a different folder from the file importing it.
- 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
import math
r = 7
print(round(math.pi * r ** 2, 2))
print(math.ceil(r / 2))153.94
4Key takeaway#
Finished this lesson?