Aral Code

Functions & Modules Lesson 19 of 23

Python Modules — math, random, datetime and Your Own

Use Python's built-in modules with import — random for games and raffles, datetime for dates and ages, math, and create your own module file. Install extra packages with pip.

A module is a file of Python code you can use in your program. Python comes with hundreds of built-in modules (the "standard library"), and thousands more can be installed for free. Using modules means you don't have to write everything yourself.

Importing a module

import math
print(math.sqrt(81))
print(math.pi)

Output

9.0
3.141592653589793

Other ways to import

from math import sqrt, pi     # import only some names
print(sqrt(81), pi)

import datetime as dt          # give the module a short nickname
print(dt.date.today().year)

Output

9.0 3.141592653589793
2026

Put all your import lines at the top of the file. That way anyone reading your code sees right away which modules it uses.

The random module

import random

print(random.randint(1, 6))                        # dice roll, 1 to 6
print(random.choice(["Ana", "Ben", "Carla"]))      # pick one
print(random.random())                             # decimal 0 to 1

numbers = list(range(1, 11))
random.shuffle(numbers)                            # mix up the order
print(numbers)

print(random.sample(range(1, 59), 6))              # 6 unique lotto numbers

Output

4
Carla
0.6394267984578837
[7, 2, 10, 5, 1, 9, 3, 8, 6, 4]
[12, 47, 3, 30, 55, 21]

Example: recitation picker

import random

students = ["Ana", "Ben", "Carla", "Dan", "Ela", "Fe"]
random.shuffle(students)
print("Recitation order:")
for i, name in enumerate(students, start=1):
    print(f"{i}. {name}")

The datetime module

from datetime import date, datetime, timedelta

today = date.today()
print(today)
print(today.year, today.month, today.day)

now = datetime.now()
print(now.strftime("%B %d, %Y  %I:%M %p"))

due = today + timedelta(days=7)
print("Due in one week:", due)

xmas = date(today.year, 12, 25)
print("Days to Christmas:", (xmas - today).days)

Output

2026-12-02
2026 12 2
December 02, 2026  10:30 AM
Due in one week: 2026-12-09
Days to Christmas: 23

strftime formats dates with codes: %Y year, %m month number, %B month name, %d day, %A weekday name, %I:%M %p 12-hour time.

Example: computing age

from datetime import date

def age(birthday):
    today = date.today()
    years = today.year - birthday.year
    if (today.month, today.day) < (birthday.month, birthday.day):
        years -= 1      # birthday hasn't happened yet this year
    return years

print(age(date(2011, 3, 14)))

Output

15

Comparing tuples (month, day) checks the month first, then the day. Neat!

Making your own module

Any .py file can be a module. Save this as grading.py:

# grading.py
PASSING = 75

def average(grades):
    return sum(grades) / len(grades)

def passed(grade):
    return grade >= PASSING

Then, in another file in the same folder:

# main.py
import grading

avg = grading.average([88, 72, 95])
print(round(avg, 2), grading.passed(avg))

Output

85.0 True

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

if __name__ == "__main__"

You'll often see this at the bottom of Python files:

if __name__ == "__main__":
    print("Testing grading.py...")
    print(average([90, 80]))

The code inside runs only when you run the file directly, not when another file imports it. It's a handy place for quick tests.

Installing packages with pip

Python's package installer, pip, downloads modules made by others. In the command prompt:

pip install requests
pip install matplotlib

Popular packages include requests (get data from websites), matplotlib (charts), pandas (spreadsheet-like data analysis) and pygame (games).

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. Which gives a random whole number from 1 to 6?
2. What does from math import sqrt let you do?
3. What tool installs extra Python packages?
4. Why shouldn't you name your file random.py?

By Sir Reyel · Last updated 2026-12-04