Lesson 10.1: Using Built-in Modules
What you will learn:
- What a module is and why modules are useful
- How to use the
mathmodule for mathematical operations - How to generate random values with the
randommodule - How to work with dates and times using
datetime
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.
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)
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
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
-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}")
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}")
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)}")
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)
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}")
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
02:30 PM
Sunday, June 15
Common Format Codes
| Code | Meaning | Example |
|---|---|---|
%Y | 4-digit year | 2025 |
%m | Month (01-12) | 06 |
%d | Day (01-31) | 15 |
%B | Full month name | June |
%A | Full weekday name | Sunday |
%H | Hour (24-hour) | 14 |
%I | Hour (12-hour) | 02 |
%p | AM/PM | PM |
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)}")
[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
- A module is a file of Python code you can reuse by importing it
- The
mathmodule provides functions likesqrt(),ceil(),floor(), and constants likepi - The
randommodule providesrandint(),choice(), andshuffle()for randomness - The
datetimemodule lets you get the current date/time and format it withstrftime() - You must
importa module before using its functions