// python · beginner

Python Modules and pip: Use Code That's Already Written

Learn how to import Python's built-in modules like random, math and datetime, split your own code into modules, and install packages safely with pip and a virtual environment.

One of Python’s biggest strengths is that you rarely have to start from scratch. Need random numbers, dates, maths or web requests? Someone has already written well-tested code for it. That code comes in modules, and learning to use them is like unlocking a huge toolbox.

What is a module?

A module is simply a Python file full of functions and variables that you can use in your own program. Python comes with hundreds of them, known as the standard library, and you load one with import:

python
import random

dice = random.randint(1, 6)
print(f"You rolled a {dice}")

After import random, everything inside the module is available with the random. prefix.

Three ways to import

python
import math
print(math.sqrt(16))        # 4.0

from math import sqrt, pi
print(sqrt(25), pi)         # 5.0 3.141592653589793

import datetime as dt
print(dt.date.today())      # e.g. 2026-11-21
  • import math keeps the prefix, so it’s always clear where sqrt came from. This is usually the best choice.
  • from math import sqrt lets you use the name directly. It’s handy for one or two names you use a lot.
  • import ... as ... gives a module a shorter nickname.

Avoid from math import *. It dumps every name into your program, and you can no longer tell where things came from.

Standard library modules worth knowing

Module Useful for Example
random random numbers and choices random.choice(["rock", "paper", "scissors"])
math square roots, rounding, pi math.ceil(4.2) → 5
datetime dates and times datetime.date.today()
time pausing and timing time.sleep(1) waits one second
pathlib working with files and folders Path("notes.txt").exists()
json saving lists and dictionaries to files json.dump(data, file)
statistics mean, median, mode statistics.mean([2, 4, 9]) → 5

Here are a few in action:

python
import random
import statistics
from datetime import date

names = ["Ava", "Leo", "Mia", "Sam"]
print(random.choice(names))          # one random name
random.shuffle(names)                # shuffles the list in place
print(names)

marks = [64, 72, 72, 90]
print(statistics.mean(marks))        # 74.5
print(statistics.median(marks))      # 72.0

exam = date(2027, 5, 14)
print(f"{(exam - date.today()).days} days until the exam")

Making your own module

Any .py file can be a module. Create a file called helpers.py:

python
# helpers.py
def greet(name):
    return f"Hello, {name}!"

def is_even(n):
    return n % 2 == 0

Then, in another file in the same folder, import it by its file name without the .py:

python
# main.py
import helpers

print(helpers.greet("Ava"))
print(helpers.is_even(10))

Splitting a growing program into a few modules keeps each file short and focused.

The if __name__ == "__main__": line

You’ll see this line in a lot of Python code:

python
# helpers.py
def greet(name):
    return f"Hello, {name}!"

if __name__ == "__main__":
    print(greet("test"))   # only runs when you run helpers.py directly

When you run a file directly, Python sets its __name__ to "__main__". When it’s imported, __name__ is the module’s name instead. So code under this if runs when you test the file on its own, but not when another file imports it.

Don’t name your file after a module. If you save your script as random.py, then import random imports your file instead of Python’s, and you’ll get confusing errors such as module ‘random’ has no attribute ‘randint’. Rename your file and delete any __pycache__ folder next to it.

Installing packages with pip

Beyond the standard library, there are hundreds of thousands of free packages on the Python Package Index (PyPI), such as requests for downloading web pages or rich for colourful terminal output. You install them with pip, which comes with Python.

The safest way is to run pip through Python, so it installs into the Python you’re actually using:

terminal
python -m pip install rich

On a Mac, use python3 -m pip install rich. Then use it like any other module:

python
from rich import print
print("[bold green]Installed and working![/bold green]")

Other useful pip commands:

terminal
python -m pip list               # show installed packages
python -m pip install --upgrade rich
python -m pip uninstall rich

Virtual environments: one toolbox per project

If every project installs packages into the same place, they eventually clash. A virtual environment gives each project its own private set of packages. Create one inside your project folder:

terminal
python -m venv .venv

Then activate it:

terminal
.venv\Scripts\activate        # Windows
source .venv/bin/activate     # Mac and Linux

Your terminal prompt now starts with (.venv), and anything you pip install goes only into this project. Type deactivate to leave. VS Code notices .venv folders automatically. See the VS Code setup guide.

Stay safe: only install packages you’ve heard of or that are widely used, and double-check the spelling. Fake packages with names close to popular ones do exist.

Mini project: a random password generator

python
import random
import string

def make_password(length=12):
    characters = string.ascii_letters + string.digits + "!?#$%&"
    return "".join(random.choice(characters) for _ in range(length))

for _ in range(3):
    print(make_password())

string.ascii_letters contains every letter a–z and A–Z, and string.digits contains 0–9. The _ is a name programmers use for a loop variable they don’t need. Challenge: for real passwords, swap random for the secrets module (secrets.choice), which is designed for security, and make sure every password contains at least one digit.

Key points

  • import module loads code; use module.name to access it.
  • The standard library includes random, math, datetime, json and many more.
  • Any .py file can be imported as a module from the same folder.
  • Install extra packages with python -m pip install name.
  • Use a virtual environment (python -m venv .venv) for each project.

Next, learn to organise bigger programs with Python Classes and Objects, then put everything together in the To-Do List App project.