Modules & the Standard Library
import mathimport brings in a module: a file of ready-made functions.
1Level 1 · BasicsBasics
You don't have to write everything yourself. Python comes with a huge standard library, ready-made modules for maths, random numbers, dates and much more. People also share packages like NumPy and pandas, which you'll use at the end of this course.
Importing a module
A module is a file of Python code you can reuse. Bring it into your program with import:
import math print(math.sqrt(16)) # 4.0 print(math.pi) # 3.141592653589793
After import math, use math. followed by the name of what you need.
Other ways to import
| Style | Then write |
|---|---|
import math | math.sqrt(9) |
from math import sqrt, pi | sqrt(9) |
import statistics as st | st.mean(data) (a short nickname) |
Avoid from math import *: it dumps every name into your program and makes it hard to tell where things came from.
Modules worth knowing
math:sqrt,ceil,floor,gcd,factorial,pirandom:randint(1, 6),choice(list),shuffle(list)datetime: today's date, differences between datesstatistics:mean,median,mode,stdevcollections:Counterfor counting,defaultdict,dequeitertools: combinations, permutations and other looping tools
Exploring a module
dir(math) lists everything inside a module, and help(math.gcd) explains one function.
Your own modules
Any .py file is a module. If you save functions in helpers.py, another file in the same folder can import helpers. Code under if __name__ == "__main__": runs only when the file is run directly, not when it's imported.
Installing packages
On your own computer you install extra packages with pip install numpy. On this site NumPy, pandas and Matplotlib load automatically when you import them.
Key points:import modulethenmodule.name;from module import nameimports one thing;asgives a nickname; explore withdir()andhelp().
See it in actionBorrowing tools from modules
import brings in ready-made functions; only the results show up as variables.
Try it yourselfExample 1: The math module
Rounding up and down, square roots and more.
Output appears hereSquare root
Fill the blanks so the program imports the math module and prints the square root of 81: 9.0.
math print(math.(81))
Forgot the module name
This should print 3.14 (pi rounded to 2 places), but it crashes. Fix it.
Ladder length
A ladder reaches 4 m up a wall with its foot 3 m away. Use math.hypot or math.sqrt to print its length: 5.0.
Example 2: Random choices
Run it several times. random.seed(1) would make the results repeat exactly.
Output appears hereExample 3: Counting with collections.Counter
Counter does the counting pattern from the Dictionaries lesson in one line.
Output appears hereMost common letter
Fill the blanks so the program finds the most common letter in mississippi and prints [('i', 4)].
from collections import print(Counter("mississippi").(1))
Example 4: Dates and statistics
date objects can be subtracted to find the days between them.
Output appears hereMean and median
Use the statistics module to print the mean and median of [2, 9, 4, 5, 10]: 6 5.
2Level 2 · IntermediateThe standard library toolbox
Python ships with hundreds of modules. A few of them solve problems you meet every week.
itertools
permutations, combinations, product and accumulate replace many hand-written nested loops.
datetime
date(2026, 12, 16) - date.today() gives days until Victory Day; timedelta(days=30) moves dates; strftime formats them.
random with a seed
random.seed(42) makes "random" results repeatable, which is great for testing. random.sample picks without repeats; random.shuffle mixes a list.
string and math
string.ascii_lowercase, math.gcd, math.comb, math.isqrt save you writing them yourself.
See it in actionitertools in action
Watch each module tool produce its results.
Example 5: Dates and countdowns
The fixed "today" keeps the output the same; replace it with date.today().
Output appears hereExample 6: Repeatable randomness and maths helpers
With the same seed, the same "random" choices come out every run.
Output appears here3Level 3 · AdvancedPackages, __name__ and how imports work
if __name__ == "__main__":
When Python runs a file directly, its __name__ is "__main__"; when it's imported, __name__ is the module's name. Put demo or test code under this check so importing the file doesn't run it.
Packages
A folder with modules (and usually an __init__.py) is a package: from shop.cart import add. Relative imports inside it use dots: from .prices import vat.
How import finds code
Python searches the folders in sys.path and imports each module once, caching it in sys.modules. A file named random.py in your folder would hide the real one, so avoid standard names.
Virtual environments
python -m venv .venv then pip install keeps each project's packages separate. pip freeze > requirements.txt records them.
Example 7: __name__ and the import cache
The file you run is called "__main__"; an imported module keeps its own name. Importing again reuses the cached module instead of loading it twice.
Output appears hereExample 8: Peeking inside modules
dir() and help-style docstrings let you explore any module.
Output appears heremath.py or random.py. Python would import your file instead of the real module, and you'd get confusing errors like AttributeError: module 'random' has no attribute 'randint'.What does this print?
import math print(math.ceil(7 / 2))
50 graded problems are waiting in Topic Practice.