Reading history

Python Modules: import, Standard Library and pip

4 min read 2 views

Learn Python modules: import forms, math, random and datetime, writing your own module, __name__ == "__main__", packages and pip.

A module is simply a Python file whose functions and variables you can use in another file. Python ships with hundreds of ready-made modules (the standard library), you can install thousands more with pip, and any .py file you write is already a module. This lesson covers the forms of import, a few essential standard modules, writing your own module, and what if __name__ == "__main__" means.

In this lesson you will learn

  • The different ways to write an import
  • Useful standard modules: math, random, datetime, statistics
  • How to create and import your own module
  • What __name__ == "__main__" is for
  • How to install third-party packages with pip

Importing Standard Modules

import math
import random as rnd
from datetime import date
from statistics import mean, median

print(math.sqrt(81), math.pi)
print(round(math.pi, 2))

rnd.seed(7)                      # fixed seed so the output repeats
print(rnd.randint(1, 6))

print(date(2026, 12, 16).strftime("%d %B %Y"))
print(mean([70, 80, 90]), median([3, 1, 2]))

Output

9.0 3.141592653589793
3.14
3
16 December 2026
80 2
  • import math loads the whole module; use its contents as math.sqrt.
  • import random as rnd gives the module a shorter name.
  • from datetime import date brings one name in directly, so you can write date(...).
  • random.seed(7) makes the “random” numbers repeat. That is useful for testing, but leave it out in real programs.

Writing Your Own Module

Save this file as geometry.py:

"""geometry.py: a small module of our own."""
PI = 3.14159

def circle_area(r):
    return PI * r * r

def _helper():
    return "private by convention"

if __name__ == "__main__":
    print("geometry.py run directly")

Then, in a second file in the same folder:

import geometry
from geometry import circle_area

print(geometry.PI)
print(circle_area(2))
print(geometry.__name__)
print([n for n in dir(geometry) if not n.startswith("__")])

Output of python main.py

3.14159
12.56636
geometry
['PI', '_helper', 'circle_area']
  • The file name, without .py, is the module name.
  • if __name__ == "__main__": is true only when you run geometry.py directly. When it is imported, __name__ is "geometry", so the test line does not print. Use this block for demo or test code.
  • A leading underscore (_helper) tells other programmers the name is meant for internal use. Python does not enforce it.
  • dir(module) lists everything a module defines.

Packages and pip

A package is a folder of modules. Third-party packages are installed from the Python Package Index with pip, for example:

python -m pip install requests

After that, import requests works like any other module. Install packages for each project inside a virtual environment (python -m venv .venv) so projects do not clash.

Handy Standard Library Modules

ModuleUse it for
mathSquare roots, rounding, trigonometry, constants
randomRandom numbers, shuffling, choosing items
datetimeDates, times and differences between them
os / pathlibFiles, folders and paths
json / csvReading and writing data files
collectionsCounter, deque, defaultdict

Common Mistakes

  1. Naming your file after a module, such as random.py or math.py. Your file is imported instead of the real one.
  2. from module import *. It hides where names come from and can overwrite your own variables.
  3. Circular imports, where two modules import each other. Move the shared code into a third module.
  4. Installing with one Python and running with another. python -m pip installs for the same Python you run.

Practice Exercises

Exercise 1. Print how many days remain until 31 December 2026 from 1 December 2026.

Show answer
from datetime import date
print((date(2026, 12, 31) - date(2026, 12, 1)).days)   # 30

Exercise 2. Count letters in “banana” using a standard module.

Show answer
from collections import Counter
print(Counter("banana"))   # Counter({'a': 3, 'n': 2, 'b': 1})

Frequently Asked Questions

What is the difference between a module and a package?

A module is a single .py file. A package is a folder that groups several modules together.

Where does Python look for modules?

First in the folder of the script being run, then in the standard library, then in installed packages. The full list is in sys.path.

Summary

  • Any .py file is a module; import lets another file use it.
  • Use import x, import x as y or from x import name.
  • if __name__ == "__main__": runs code only when the file is run directly.
  • Install third-party packages with python -m pip install.
Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *