BrightPath
Back to Course
Year 11 Coding

Python Modules and Libraries

Learn to use import, from...import, and explore built-in modules like math, random, and os. Create your own modules too.

Importing Modules

A module is a file containing Python code (functions, variables, classes) that you can reuse. Python comes with hundreds of built-in modules in its Standard Library. You import them with the import keyword.

# Method 1: Import the entire module
import math
print(math.pi)          # 3.141592653589793
print(math.sqrt(144))   # 12.0

# Method 2: Import specific items
from math import pi, sqrt
print(pi)               # 3.141592653589793
print(sqrt(64))         # 8.0

# Method 3: Import with an alias
import math as m
print(m.ceil(4.3))      # 5 (round up)
print(m.floor(4.7))     # 4 (round down)
Tip: Use from module import name for specific items, or import module for the whole thing.

The random Module

The random module generates random numbers and makes random choices. It is useful for games, simulations, and data sampling.

import random

# Random integer between 1 and 10 (inclusive)
dice_roll = random.randint(1, 6)
print(f"Dice: {dice_roll}")

# Random float between 0 and 1
chance = random.random()
print(f"Random: {chance:.4f}")

# Random choice from a list
colours = ["red", "blue", "green", "yellow"]
pick = random.choice(colours)
print(f"Picked: {pick}")

# Shuffle a list in place
cards = ["A", "K", "Q", "J", "10"]
random.shuffle(cards)
print(f"Shuffled: {cards}")

# Random sample (pick n items without repeats)
winners = random.sample(["Alice", "Bob", "Charlie", "Diana"], 2)
print(f"Winners: {winners}")

The os Module and Creating Your Own Modules

The os module lets you interact with the operating system. You can also create your own modules by saving functions in a .py file and importing it.

import os

# Get current working directory
print(os.getcwd())

# List files in a directory
files = os.listdir(".")
print(f"Files: {files[:5]}")  # First 5 files

# Check if a file exists
print(os.path.exists("data.txt"))

# --- Creating your own module ---
# Save this in a file called "helpers.py":
# def greet(name):
#     return f"Hello, {name}!"
#
# def add(a, b):
#     return a + b

# Then in your main program:
# import helpers
# print(helpers.greet("Alice"))
# print(helpers.add(3, 5))

Key Vocabulary

Module

A Python file (.py) containing reusable code: functions, variables, and classes.

Library

A collection of modules. Python's Standard Library includes hundreds of built-in modules.

import

The keyword used to load a module so you can use its functions and data in your program.

Alias

A shorter name for a module using import module as alias, e.g. import math as m.

Worked Examples

1

Build a simple calculator using the math module

import math

radius = 5
area = math.pi * radius ** 2
circumference = 2 * math.pi * radius

print(f"Circle with radius {radius}:")
print(f"  Area: {area:.2f}")
print(f"  Circumference: {circumference:.2f}")
print(f"  Square root of area: {math.sqrt(area):.2f}")

Step 1: Import math to access math.pi and math.sqrt().

Output: Area: 78.54 | Circumference: 31.42 | Square root of area: 8.86

2

Create a dice game with the random module

import random

def roll_dice():
    return random.randint(1, 6)

# Simulate 5 rounds
player_score = 0
computer_score = 0

for round_num in range(1, 6):
    player = roll_dice()
    computer = roll_dice()
    print(f"Round {round_num}: You={player}, Computer={computer}", end=" ")
    if player > computer:
        player_score += 1
        print("- You win!")
    elif computer > player:
        computer_score += 1
        print("- Computer wins!")
    else:
        print("- Draw!")

print(f"\nFinal: You {player_score} - {computer_score} Computer")

Step 1: We use random.randint(1, 6) to simulate dice rolls.

Step 2: Track scores over 5 rounds and display the winner.

3

Generate a random password using random and string modules

import random
import string

def generate_password(length=12):
    # Combine all character types
    characters = string.ascii_letters + string.digits + string.punctuation

    # Ensure at least one of each type
    password = [
        random.choice(string.ascii_uppercase),
        random.choice(string.ascii_lowercase),
        random.choice(string.digits),
        random.choice(string.punctuation)
    ]

    # Fill the rest randomly
    for i in range(length - 4):
        password.append(random.choice(characters))

    random.shuffle(password)
    return "".join(password)

print(f"Password: {generate_password()}")
print(f"Short: {generate_password(8)}")

Step 1: We import both random and string modules.

Step 2: The string module provides character sets like ascii_letters and digits.

Knowledge Check

Select the correct answer for each question. Click "Check Answer" to see if you are right.

Question 1

Which statement correctly imports only sqrt from the math module?

Question 2

What does random.randint(1, 10) return?

Question 3

What does import math as m do?

Question 4

What does math.floor(4.9) return?

Question 5

To create your own module, you save your functions in a file ending with:

Key Concepts Summary

Previous: Python Error Handling Back to All Lessons