Modules and the standard library
Use import to load Python modules such as math, random, datetime and statistics, split your own code into modules, and install extra packages safely with pip and a virtual environment.
🎯 By the end of this lesson you will be able to:
- Import and use modules from Python's standard library
- Split your own code into a module and import it
- Explain what pip and a virtual environment are for
Outline
What you'll learn and why it matters
Python comes with hundreds of ready-made tools for dates, random numbers, maths, files, the internet and more. This collection is called the standard library, and it is organised into modules: files of Python code you can load into your program with import. Knowing what is already available saves you from writing everything yourself.
Importing a module
You already used one module: import csv in lesson 12. The pattern is always the same: import the module, then use its tools with a dot.
import math
print(math.sqrt(144))
print(math.pi)
print(math.ceil(4.2))
print(math.floor(4.8))Output
12.0 3.141592653589793 5 4
math.sqrt means “the sqrt function from the math module”. ceil rounds up and floor rounds down. A handy use of ceil: 23 people need math.ceil(23 / 5) = 5 cars, not 4.6.
You can also import just the names you need, so you can use them without the module name:
from math import sqrt, pi
print(round(pi * sqrt(2), 3))Output
4.443
Put all your imports at the top of the file, so readers can see what your program depends on.
A short tour of useful modules
| Module | Use it for | Example |
|---|---|---|
math | Square roots, rounding up or down, pi | math.ceil(4.2) → 5 |
random | Random numbers and choices | random.randint(1, 6) → a dice roll |
datetime | Dates, times and date arithmetic | date.today() |
statistics | Mean, median and mode | statistics.median([3, 1, 2]) → 2 |
csv | Reading and writing CSV files | csv.DictReader(file) |
pathlib | Working with file paths and folders | Path("data").exists() |
random: making games and samples
import random
roll = random.randint(1, 6)
snack = random.choice(["samosa", "idli", "vada pav"])
print(f"You rolled a {roll}. Today's snack: {snack}")randint(1, 6) gives a whole number from 1 to 6 (including both). choice() picks one item from a list. Now you can finish the guessing game from lesson 9 properly: replace secret = 7 with secret = random.randint(1, 10).
datetime: working with dates
from datetime import date
exam = date(2026, 12, 15)
today = date(2026, 11, 25)
days_left = (exam - today).days
print(f"Exam on {exam:%d %B %Y}")
print(f"{days_left} days to go")
print(f"That is about {days_left // 7} weeks")Output
Exam on 15 December 2026 20 days to go That is about 2 weeks
Subtracting two dates gives a timedelta (a length of time); .days is the number of days in it. In a real program you would use date.today() instead of a fixed date. The f-string code %d %B %Y formats the date as day, full month name and year.
statistics: quick summaries
import statistics
marks = [78, 91, 66, 84, 72, 91]
print("Mean:", round(statistics.mean(marks), 1))
print("Median:", statistics.median(marks))
print("Most common:", statistics.mode(marks))Output
Mean: 80.3 Median: 81.0 Most common: 91
The mean is the usual average. The median is the middle value when the numbers are sorted (with an even count, the average of the two middle ones), and is less affected by one very high or low value.
Your own modules
Any .py file is a module. Put helper functions in one file and import them from another, as long as both files are in the same folder:
def add_gst(price, percent=18):
return price + price * percent / 100
def format_rupees(amount):
return f"₹{amount:,.2f}"import money
price = money.add_gst(1200)
print(money.format_rupees(price))Output
₹1,416.00
:,.2f adds a comma as a thousands separator. Splitting code like this keeps each file short and lets you reuse your functions in many programs.
Beyond the standard library: pip and virtual environments
Thousands more packages, such as requests for websites or pandas for data analysis, are shared on the Python Package Index (PyPI). You install them with pip, which comes with Python. You will not need any for this course, but here is the safe way to do it when you do.
A virtual environment is a private folder of packages for one project, so projects do not interfere with each other. Run these commands in a terminal, inside your project folder:
# 1. Create a virtual environment in a folder called .venv
python -m venv .venv
# 2. Turn it on (activate it)
.venv\Scripts\activate # Windows
source .venv/bin/activate # macOS and Linux
# 3. Install a package into it
python -m pip install requestsWhen the environment is active, your terminal prompt starts with (.venv). Type deactivate to turn it off. To undo everything, simply delete the .venv folder.
Practice
Guided exercise
Days until your birthday
Using from datetime import date, set today = date(2026, 11, 25) and your next birthday as another date. Print how many days are left.
- Import
datefromdatetime. - Create the two dates with
date(year, month, day). - Subtract them and use
.days.
Show the solution
from datetime import date
today = date(2026, 11, 25)
birthday = date(2027, 2, 14)
print(f"{(birthday - today).days} days until my birthday")Output
81 days until my birthday
How to get there: From 25 November to 14 February is 5 + 31 + 31 + 14 = 81 days. Use date.today() in your own version so it is always up to date.
Your turn
Cars needed
A trip has 47 students and each car takes 4. Use math.ceil to print how many cars are needed.
Show the solution
import math
students = 47
per_car = 4
print(f"Cars needed: {math.ceil(students / per_car)}")Output
Cars needed: 12
How to get there: 47 / 4 is 11.75. You cannot book three-quarters of a car, so round up with ceil to 12. round() would give 12 here too, but would wrongly round 11.25 down to 11.
Common mistakes
Using a module without importing it
You see: NameError: name 'math' is not defined
Fix: Add import math at the top of the file.
Naming your file the same as a module
You see: AttributeError: module 'random' has no attribute 'randint'
Fix: Rename your file (e.g. dice_game.py) and delete __pycache__.
Running pip inside the Python shell
You see: SyntaxError at >>> pip install ...
Fix: pip commands go in a terminal, not after >>>. Use python -m pip install name.
Installing packages without a virtual environment
You see: Version conflicts between projects later
Fix: Create and activate a .venv for each project first.
Recap
- A module is a file of Python code;
import nameloads it andname.tooluses it. - The standard library includes math, random, datetime, statistics, csv and pathlib.
- Your own
.pyfiles are modules too. Never name them after a standard module. - Install extra packages with
python -m pip installinside a virtual environment.
Key terms
- Module
- A file of Python code you can import into other programs.
- Standard library
- The modules that come with Python.
- pip
- The tool that installs extra packages from the Python Package Index.
- Virtual environment
- A private set of installed packages for one project.
Check your understanding
Answer all 4 questions, then check your answers to see an explanation for each one.
1. After `import math`, how do you call the square root function?
2. Which numbers can `random.randint(1, 6)` return?
3. You saved your game as random.py and now get `AttributeError: module 'random' has no attribute 'randint'`. Why?
4. What is a virtual environment for?
Read more
- The Python standard library (official docs) ↗
- Virtual environments and packages (official tutorial) ↗
Mark this lesson complete
Finished this lesson?
When you have worked through the examples and exercises, mark it complete to save your progress.