Learn Without Walls
← Module 10 Home Lesson 1 of 4 Next Lesson →

Lesson 10.1: Using Built-in Modules

What you will learn:

1. What Are Modules?

A module is a file containing Python code that you can reuse in your programs. Python comes with hundreds of built-in modules called the standard library. Instead of writing everything from scratch, you can import these modules and use the functions they provide.

Module: A Python file (.py) containing functions, classes, and variables that you can use in other programs by importing it.

Think of modules like apps on your phone. Your phone comes with built-in apps (like a calculator and calendar), and you can also download more apps. Similarly, Python comes with built-in modules, and you can install additional ones.

To use a module, you first need to import it:

import math

# Now you can use functions from the math module
result = math.sqrt(16)
print(result)
4.0

2. The math Module

The math module provides mathematical functions beyond basic arithmetic. Here are some of the most useful ones:

Square Root

import math

# sqrt() returns the square root of a number
print(math.sqrt(25))    # 5.0
print(math.sqrt(2))     # 1.4142135623730951
print(math.sqrt(100))   # 10.0
5.0
1.4142135623730951
10.0

Rounding: ceil() and floor()

import math

# ceil() rounds UP to the nearest integer
print(math.ceil(3.2))    # 4
print(math.ceil(3.9))    # 4
print(math.ceil(-2.3))   # -2

# floor() rounds DOWN to the nearest integer
print(math.floor(3.2))   # 3
print(math.floor(3.9))   # 3
print(math.floor(-2.3))  # -3
4
4
-2
3
3
-3

Using math.pi

import math

# math.pi is a constant (not a function)
print(math.pi)  # 3.141592653589793

# Calculate the area of a circle
radius = 5
area = math.pi * radius ** 2
print(f"Area of circle: {area:.2f}")
3.141592653589793
Area of circle: 78.54

Try It Yourself

Use the math module to calculate the hypotenuse of a right triangle with sides 3 and 4. Remember: hypotenuse = sqrt(a^2 + b^2).

3. The random Module

The random module lets you generate random numbers and make random choices. This is useful for games, simulations, and any program that needs unpredictability.

randint() - Random Integer

import random

# randint(a, b) returns a random integer from a to b (inclusive)
dice_roll = random.randint(1, 6)
print(f"You rolled a {dice_roll}")

# Generate a random number between 1 and 100
number = random.randint(1, 100)
print(f"Random number: {number}")
You rolled a 4
Random number: 73

choice() - Random Selection

import random

# choice() picks a random item from a list
colors = ["red", "blue", "green", "yellow"]
picked = random.choice(colors)
print(f"Random color: {picked}")

# Works with any sequence
meals = ["pizza", "tacos", "sushi", "pasta"]
print(f"Tonight's dinner: {random.choice(meals)}")
Random color: green
Tonight's dinner: tacos

shuffle() - Shuffle a List

import random

# shuffle() rearranges a list in place (modifies the original)
cards = ["Ace", "King", "Queen", "Jack", "10"]
print("Before:", cards)

random.shuffle(cards)
print("After:", cards)
Before: ['Ace', 'King', 'Queen', 'Jack', '10']
After: ['Queen', '10', 'Ace', 'Jack', 'King']

4. The datetime Module

The datetime module helps you work with dates and times. You can get the current date, format dates as strings, and perform date calculations.

Getting the Current Date and Time

from datetime import datetime

# Get the current date and time
now = datetime.now()
print(now)

# Access individual parts
print(f"Year: {now.year}")
print(f"Month: {now.month}")
print(f"Day: {now.day}")
print(f"Hour: {now.hour}")
print(f"Minute: {now.minute}")
2025-06-15 14:30:22.123456
Year: 2025
Month: 6
Day: 15
Hour: 14
Minute: 30

Formatting Dates

from datetime import datetime

now = datetime.now()

# strftime() formats a date as a string
# %B = full month name, %d = day, %Y = 4-digit year
formatted = now.strftime("%B %d, %Y")
print(formatted)  # June 15, 2025

# %I = 12-hour, %M = minute, %p = AM/PM
time_str = now.strftime("%I:%M %p")
print(time_str)   # 02:30 PM

# %A = day of the week
day_str = now.strftime("%A, %B %d")
print(day_str)    # Sunday, June 15
June 15, 2025
02:30 PM
Sunday, June 15

Common Format Codes

Code Meaning Example
%Y4-digit year2025
%mMonth (01-12)06
%dDay (01-31)15
%BFull month nameJune
%AFull weekday nameSunday
%HHour (24-hour)14
%IHour (12-hour)02
%pAM/PMPM

5. Combining Modules in a Program

You can use multiple modules together in the same program. Here is an example that uses all three modules:

A Simple Lottery Number Generator

import math
import random
from datetime import datetime

# Generate 5 lottery numbers between 1 and 50
numbers = []
for i in range(5):
    num = random.randint(1, 50)
    numbers.append(num)

# Sort the numbers
numbers.sort()

# Display results with today's date
today = datetime.now().strftime("%B %d, %Y")
print(f"Lottery numbers for {today}:")
print(numbers)

# Calculate the sum using math.fsum for precision
total = math.fsum(numbers)
print(f"Sum of numbers: {int(total)}")
Lottery numbers for June 15, 2025:
[7, 12, 23, 38, 45]
Sum of numbers: 125

Check Your Understanding

What is the difference between math.ceil(3.1) and math.floor(3.9)?

math.ceil(3.1) returns 4 (rounds up to the next integer), while math.floor(3.9) returns 3 (rounds down to the previous integer). ceil always rounds toward positive infinity, and floor always rounds toward negative infinity.

Key Takeaways

← Module 10 Home Lesson 1 of 4 Next Lesson →