Introduction to Libraries (math, random, datetime)
What you'll learn
- What a library is and why we use it
- How to import and use three handy standard libraries: math, random, and datetime
- Simple, practical examples
- A short mini project that uses all three
What are libraries?
Think of a library as a toolkit you can plug into your Python program. Instead of reinventing the wheel, you import a library and instantly get new functions and features—like square roots, random numbers, or working with dates and times.
How to import libraries
- Import the whole library:
import math x = math.sqrt(25) - Import specific names:
from math import sqrt x = sqrt(25) - Give a short nickname (alias):
import datetime as dt now = dt.datetime.now()
Part 1: math — math tools you'll actually use
Common functions:
- math.sqrt(x): square root
- math.pow(a, b) or a**b: powers
- math.pi: the number π
- math.ceil(x) and math.floor(x): round up or down
- math.radians(deg) and math.degrees(rad): convert angles
Example:
import math
print("Square root of 49:", math.sqrt(49))
print("2 to the power of 5:", math.pow(2, 5)) # same as 2**5
print("Pi:", math.pi)
print("Ceil of 3.1:", math.ceil(3.1))
print("Floor of 3.9:", math.floor(3.9))
print("30 degrees in radians:", math.radians(30))
print("π/3 radians in degrees:", math.degrees(math.pi / 3))Part 2: random — make your program less predictable
Common functions:
- random.random(): a float from 0.0 up to (but not including) 1.0
- random.randint(a, b): an integer between a and b, inclusive
- random.choice(seq): pick one item from a list or string
- random.shuffle(list): shuffle a list in place
- random.sample(seq, k): pick k unique items
Example:
import random
print("Random float 0–1:", random.random())
print("Dice roll (1–6):", random.randint(1, 6))
students = ["Ava", "Ben", "Cara", "Diego"]
print("Random student:", random.choice(students))
cards = ["A", "2", "3", "4", "5"]
random.shuffle(cards)
print("Shuffled cards:", cards)
lotto = random.sample(range(1, 50), 6)
print("Lottery picks:", lotto)Part 3: datetime — dates, times, and countdowns
Useful pieces:
- date.today(): today's date (YYYY-MM-DD)
- datetime.now(): current date and time
- strftime: format a date/time as text
- timedelta: add or subtract time
Example:
from datetime import date, datetime, timedelta
today = date.today()
print("Today:", today)
now = datetime.now()
print("Now (formatted):", now.strftime("%Y-%m-%d %H:%M:%S"))
# Days until a specific date (change the date if you like!)
end_of_term = date(today.year, 6, 30)
days_left = (end_of_term - today).days
print("Days until end of term:", days_left)
future = now + timedelta(days=7, hours=2)
print("In 7 days and 2 hours:", future.strftime("%A %I:%M %p"))Mini Project: Speed Math Quiz (uses math, random, datetime)
What it does:
- Asks you 3 quick math questions (+, -, *, or square root)
- Measures how long you take for each question
- Shows your score and the finish time
Code:
import random
import math
from datetime import datetime
print("Speed Math Quiz")
print("----------------")
score = 0
num_qs = 3
for i in range(1, num_qs + 1):
op = random.choice(["+", "-", "*", "sqrt"])
if op == "sqrt":
# Use perfect squares so the answers are whole numbers
n = random.choice([1, 4, 9, 16, 25, 36, 49, 64, 81, 100])
correct = int(math.sqrt(n))
prompt = f"Q{i}: What is the square root of {n}? "
else:
a = random.randint(1, 12)
b = random.randint(1, 12)
if op == "-":
# Keep the result non-negative
a, b = max(a, b), min(a, b)
if op == "+":
correct = a + b
prompt = f"Q{i}: {a} + {b} = "
elif op == "-":
correct = a - b
prompt = f"Q{i}: {a} - {b} = "
else:
correct = a * b
prompt = f"Q{i}: {a} * {b} = "
start = datetime.now()
try:
answer = int(input(prompt))
except ValueError:
answer = None
end = datetime.now()
secs = (end - start).total_seconds()
if answer == correct:
print(f" Correct! ({secs:.1f}s)")
score += 1
else:
print(f" Oops! The answer was {correct}. ({secs:.1f}s)")
finish_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print("----------------")
print(f"You scored {score}/{num_qs}. Finished at {finish_time}.")Ideas to extend:
- Add division questions (careful with rounding)
- Make it 10 questions and show your average time
- Give extra points if you answer in under 3 seconds
Summary
- Libraries are toolkits that add power to Python without extra work.
- math gives you functions like sqrt, pow, pi, ceil, and conversions between degrees/radians.
- random helps you pick numbers or items unpredictably: random(), randint, choice, shuffle, sample.
- datetime lets you work with dates and times: today, now, formatting, and time differences with timedelta.
- You practiced all three with a fun, timed quiz.