LearnPy Hub
FunctionsIntermediateLesson 15 of 32

Modules & the Standard Library

Watch the ideaBorrow ready-made tools
import math
math module
import
your program

import 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

StyleThen write
import mathmath.sqrt(9)
from math import sqrt, pisqrt(9)
import statistics as stst.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, pi
  • random: randint(1, 6), choice(list), shuffle(list)
  • datetime: today's date, differences between dates
  • statistics: mean, median, mode, stdev
  • collections: Counter for counting, defaultdict, deque
  • itertools: 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 module then module.name; from module import name imports one thing; as gives a nickname; explore with dir() and help().

See it in actionBorrowing tools from modules

import brings in ready-made functions; only the results show up as variables.

Step-by-step

Try it yourselfExample 1: The math module

Rounding up and down, square roots and more.

example_1.py
Output appears here
Fill in the blanks

Square root

Fill the blanks so the program imports the math module and prints the square root of 81: 9.0.

blanks.py
 math
print(math.(81))
Fix the bug

Forgot the module name

This should print 3.14 (pi rounded to 2 places), but it crashes. Fix it.

buggy.py
Your turn

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.

my_code.py

Example 2: Random choices

Run it several times. random.seed(1) would make the results repeat exactly.

example_2.py
Output appears here

Example 3: Counting with collections.Counter

Counter does the counting pattern from the Dictionaries lesson in one line.

example_3.py
Output appears here
Fill in the blanks

Most common letter

Fill the blanks so the program finds the most common letter in mississippi and prints [('i', 4)].

blanks.py
from collections import 
print(Counter("mississippi").(1))

Example 4: Dates and statistics

date objects can be subtracted to find the days between them.

example_4.py
Output appears here
Your turn

Mean and median

Use the statistics module to print the mean and median of [2, 9, 4, 5, 10]: 6 5.

my_code.py

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.

Step-by-step

Example 5: Dates and countdowns

The fixed "today" keeps the output the same; replace it with date.today().

example_5.py
Output appears here

Example 6: Repeatable randomness and maths helpers

With the same seed, the same "random" choices come out every run.

example_6.py
Output appears here

3Level 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.

example_7.py
Output appears here

Example 8: Peeking inside modules

dir() and help-style docstrings let you explore any module.

example_8.py
Output appears here
Common mistakeDon't name your own file math.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'.
Exercise · predict the output

What does this print?

import math
print(math.ceil(7 / 2))
Quick quiz · 5 questions
1. After from math import sqrt, how do you call it?
2. Which module would you use for a random dice roll?
3. What does import pandas as pd do?
4. What does Counter("aab") give?
5. Which function lists everything inside a module?
Ready to practice modules & the standard library?

50 graded problems are waiting in Topic Practice.

Practice this topic →
Python Modules & the Standard Library · LearnPy Hub