📘 Lesson 16 · Intermediate

Python Modules

Import and use Python modules, create your own, and explore the standard library.

What is a Module?

A module is simply a Python file containing functions, classes, and variables that you can reuse across other programs. Instead of rewriting common functionality, you import it. Python ships with a vast standard library of built-in modules: math, os, json, datetime, random, and hundreds more. Thousands of additional modules are available via pip.

Importing and Using Modules

The import statement loads a module. Access its contents using dot notation: module.function(). This keeps your namespace clean — two modules can have functions with the same name without conflict.

import.py
import math

print(math.pi)           # the value of π
print(math.sqrt(144))    # square root
print(math.ceil(4.2))    # round UP to 5
print(math.floor(4.9))   # round DOWN to 4
print(math.factorial(5))  # 5! = 120
▶ Output
3.141592653589793
12.0
5
4
120

from ... import and Aliases

from module import name imports specific items directly — no prefix needed. import module as alias gives the module a short name (convention: numpy → np, pandas → pd).

from_alias.py
from math import sqrt, pi
print(sqrt(81))   # no "math." needed
print(pi)

import random as rnd
print(rnd.randint(1, 100))
print(rnd.choice(["rock", "paper", "scissors"]))
▶ Output
9.0
3.141592653589793
47
rock

Creating Your Own Module

Any .py file is a module. Save functions in a file, then import it from another script in the same folder. This is how large projects are split into organised files.

myutils.py
# myutils.py — helper functions
def square(n): return n ** 2
def is_even(n): return n % 2 == 0
main.py
import myutils
print(myutils.square(5))
print(myutils.is_even(7))
▶ Output
25
False
Use dir(module) to see all functions and attributes a module provides. Use help(module.function) to read its documentation.

🧠 Quick Check

What does 'import math as m' allow you to do?

Rename math permanently
Use m.sqrt() instead of math.sqrt()
Import only sqrt
Create a copy

Tags

modulesimportstandard librarymathosrandomalias