Unit 4 · Modules and File Handling
Built-in Modules (math, random, datetime)
Master Python's essential built-in modules: math for mathematical operations, random for number generation, and datetime for date and time manipulation.
Introduction
Python comes with a rich standard library of built-in modules that provide ready-made functions for common tasks. The math, random, and datetime modules are among the most frequently used in academic and real-world programming.
Understanding these modules is essential for university exams, as questions frequently test knowledge of specific functions like sqrt(), randint(), strftime(), and timedelta().
University Definition
Built-in modules are pre-written Python modules that ship with the Python interpreter. They provide commonly used functionality such as mathematical operations (math), random number generation (random), and date/time handling (datetime) without requiring external installation.
Table of Contents
The math Module
The math module provides access to mathematical functions defined by the C standard. It includes functions for basic arithmetic, logarithms, trigonometry, and number theory.
| Function | Description | Example |
|---|---|---|
| sqrt(x) | Square root of x | math.sqrt(25) → 5.0 |
| pow(x, y) | x raised to the power y | math.pow(2, 10) → 1024.0 |
| ceil(x) | Smallest integer ≥ x | math.ceil(4.3) → 5 |
| floor(x) | Largest integer ≤ x | math.floor(4.7) → 4 |
| factorial(n) | n factorial (n!) | math.factorial(5) → 120 |
| pi | Constant: 3.14159... | math.pi → 3.14159265... |
| e | Constant: 2.71828... | math.e → 2.71828182... |
| log(x[, base]) | Logarithm of x | math.log(100, 10) → 2.0 |
| fabs(x) | Absolute value of x | math.fabs(-7) → 7.0 |
import math print(math.sqrt(144)) # 12.0 print(math.pow(2, 8)) # 256.0 print(math.ceil(4.2)) # 5 print(math.floor(4.8)) # 4 print(math.factorial(6)) # 720 print(math.pi) # 3.141592653589793 print(math.log(1000, 10)) # 3.0 print(math.fabs(-42)) # 42.0 print(math.sqrt(-1)) # ValueError: math domain error
University Exam Tip
ceil() and floor() always return integers. sqrt() and pow() always return floats. factorial() returns an integer. Remember: ceil(-4.2) = -4 (rounds towards positive infinity).
The random Module
The random module provides functions for generating random numbers, making random selections, and shuffling sequences.
| Function | Description | Example |
|---|---|---|
| random() | Random float in [0.0, 1.0) | random.random() → 0.743 |
| randint(a, b) | Random integer in [a, b] (inclusive) | random.randint(1, 10) → 7 |
| choice(seq) | Random element from a sequence | random.choice([1,2,3]) → 2 |
| shuffle(list) | Shuffles a list in place | random.shuffle(lst) |
| seed(n) | Sets seed for reproducibility | random.seed(42) |
| randrange(start, stop, step) | Random element from range | random.randrange(0, 100, 5) |
| sample(population, k) | k unique random elements | random.sample(range(10), 3) |
import random
# Reproducible results using seed
random.seed(42)
print(random.random()) # 0.6394267984578837
print(random.randint(1, 100)) # 36
print(random.choice(["red", "green", "blue"])) # green
# Shuffle a list
cards = [1, 2, 3, 4, 5]
random.shuffle(cards)
print(cards) # e.g., [3, 1, 5, 2, 4]
# Sample without replacement
lottery = random.sample(range(1, 50), 6)
print("Lottery numbers:", sorted(lottery))
University Exam Tip
randint(a, b) includes both endpoints. randrange(a, b) excludes b. shuffle() modifies the list in place and returns None — do not assign its result!
The datetime Module
The datetime module provides classes for working with dates, times, and time intervals.
date Object
from datetime import date
# Create a date object
d = date(2025, 12, 25)
print(d) # 2025-12-25
print(d.year) # 2025
print(d.month) # 12
print(d.day) # 25
print(d.weekday()) # 4 (Friday, Monday=0)
# Today's date
today = date.today()
print(today) # Current date
print(today.strftime("%d/%m/%Y")) # e.g., "15/06/2025"
time Object
from datetime import time t = time(14, 30, 45) # 2:30:45 PM print(t) # 14:30:45 print(t.hour) # 14 print(t.minute) # 30 print(t.second) # 45
datetime Object
from datetime import datetime
# Create datetime object
dt = datetime(2025, 8, 15, 10, 30, 0)
print(dt) # 2025-08-15 10:30:00
# Current datetime
now = datetime.now()
print(now)
# Formatting with strftime
print(now.strftime("%Y-%m-%d %H:%M:%S")) # "2025-06-15 14:30:45"
print(now.strftime("%d %B %Y")) # "15 June 2025"
print(now.strftime("%A, %d %b %Y")) # "Sunday, 15 Jun 2025"
# Parsing with strptime
date_string = "15/06/2025"
parsed = datetime.strptime(date_string, "%d/%m/%Y")
print(parsed) # 2025-06-15 00:00:00
timedelta
from datetime import datetime, timedelta
now = datetime.now()
# Add 30 days
future = now + timedelta(days=30)
print("30 days later:", future)
# Subtract 7 days
past = now - timedelta(days=7)
print("7 days ago:", past)
# Difference between two dates
d1 = datetime(2025, 12, 31)
d2 = datetime(2025, 1, 1)
diff = d1 - d2
print("Days between:", diff.days) # 364
| Format Code | Description | Example Output |
|---|---|---|
| %Y | 4-digit year | 2025 |
| %m | Month (01-12) | 06 |
| %d | Day (01-31) | 15 |
| %H | Hour (00-23) | 14 |
| %M | Minute (00-59) | 30 |
| %S | Second (00-59) | 45 |
| %A | Full weekday name | Sunday |
| %B | Full month name | June |
| %p | AM/PM | PM |
University Exam Tip
strftime = "string format time" (datetime object to string). strptime = "string parse time" (string to datetime object). The format codes must match exactly or you get a ValueError.
Practical Examples
Example 1: Calculate Age from Birthday
from datetime import date
def calculate_age(birth_date):
today = date.today()
age = today.year - birth_date.year
if (today.month, today.day) < (birth_date.month, birth_date.day):
age -= 1
return age
birthday = date(2000, 5, 15)
print(f"Age: {calculate_age(birthday)} years")
Example 2: Dice Roll Simulator
import random
def roll_dice(num_rolls=1):
results = [random.randint(1, 6) for _ in range(num_rolls)]
return results
print("Single roll:", roll_dice()[0])
print("10 rolls:", roll_dice(10))
print("Total:", sum(roll_dice(10)))
Example 3: Days Until New Year
from datetime import date
today = date.today()
new_year = date(today.year + 1, 1, 1)
days_left = (new_year - today).days
print(f"Days until New Year: {days_left}")
Key Points
math.sqrt() raises ValueError for negative numbers.
random.shuffle() returns None — it modifies the list in place.
random.randint(a, b) includes both a and b.
strftime() converts datetime to string; strptime() parses string to datetime.
math.ceil() rounds up; math.floor() rounds down.
random.seed(n) makes random results reproducible.
timedelta supports days, seconds, microseconds, minutes, hours, weeks.
date.today() returns the current local date.
Practice Questions
Q1: What is the difference between ceil() and floor()?
Answer: ceil() returns the smallest integer greater than or equal to x. floor() returns the largest integer less than or equal to x.
Q2: What will random.randint(1, 5) return?
Answer: A random integer from 1 to 5 (inclusive of both 1 and 5).
Q3: Convert today's date to the format "DD-MM-YYYY" using datetime.
Answer: from datetime import date; print(date.today().strftime("%d-%m-%Y"))
Q4: What is the output of math.ceil(4.1) and math.floor(4.9)?
Answer: math.ceil(4.1) = 5, math.floor(4.9) = 4.
Q5: How do you generate a random number between 1 and 100 using the random module?
Answer: Use random.randint(1, 100) or random.randrange(1, 101).
Summary
math module provides sqrt(), pow(), ceil(), floor(), factorial(), and constants like pi.
random module provides random(), randint(), choice(), shuffle(), seed().
datetime module provides date, time, datetime, and timedelta classes.
Use strftime() to format dates as strings, strptime() to parse strings as dates.
random.seed() makes random number generation reproducible for testing.
shuffle() modifies in place (returns None); sample() returns a new list.