Python Standard Library Core
Python follows a philosophy known as "Batteries Included". This means the standard library ships with an immense collection of battle-tested, high-performance C-optimized modules ready for immediate use without installing external packages.
The math module provides access to mathematical functions defined by the C standard library:
- Constants:
math.pi(3.14159...),math.e(2.71828...),math.tau($2\pi$),math.inf,math.nan. - Rounding:
math.floor()(rounds down),math.ceil()(rounds up),math.trunc()(truncates decimals). - Power & Logarithms:
math.sqrt(),math.pow(),math.log()(natural log),math.log10(),math.log2(). - Combinatorics:
math.factorial(n),math.comb(n, k)(combinations),math.gcd(a, b)(greatest common divisor).
import math
# 1. Rounding operations
print("Ceil of 4.2: ", math.ceil(4.2)) # 5
print("Floor of 4.8:", math.floor(4.8)) # 4
# 2. Factorial and Combinations
print("\n5! (Factorial):", math.factorial(5)) # 120
print("Combinations of 5 choose 2:", math.comb(5, 2)) # 10
# 3. Trigonometry and Geometry (Angles in Radians)
angle_rad = math.radians(90) # Convert 90 degrees to pi/2 radians
print("sin(90 degrees):", math.sin(angle_rad))
print("Hypotenuse of 6 and 8:", math.hypot(6, 8)) # 10.0
Never use float1 == float2 for decimals due to IEEE 754 precision issues (e.g. 0.1 + 0.2 != 0.3). Always use math.isclose(a, b, rel_tol=1e-9) for safe float comparisons.
The random module implements a Pseudo-Random Number Generator (PRNG) based on the famous Mersenne Twister algorithm (period of $2^{19937}-1$).
random.randint(a, b): Returns a random integer $N$ such that $a \le N \le b$ (both endpoints inclusive!).random.random(): Returns a random float in the range $[0.0, 1.0)$.random.choice(sequence): Picks a single random element from a list, string, or tuple.random.choices(seq, k=n): Selects $n$ items with replacement (duplicates possible).random.sample(seq, k=n): Selects $n$ unique items without replacement.random.shuffle(list): Randomizes list elements in place.random.seed(x): Initializes the PRNG with a fixed seed, making randomized outputs 100% deterministic and reproducible for scientific experiments.
import random
# 1. Generating random integers and floats
dice_roll = random.randint(1, 6)
random_prob = random.random()
print(f"๐ฒ Rolled a dice: {dice_roll} | Probability: {random_prob:.4f}")
# 2. Random selection from lists
participants = ["Alex", "Balaji", "Chloe", "David", "Elena", "Faisal"]
winner = random.choice(participants)
print(f"๐ Lucky Winner (choice): {winner}")
# 3. Unique sampling without replacement (Lottery / Team selection)
team = random.sample(participants, k=3)
print(f"๐ฅ Selected Team (3 unique members): {team}")
# 4. In-place shuffling of a deck of cards
cards = ["Aโ ", "Kโฅ", "Qโฆ", "Jโฃ", "10โ "]
random.shuffle(cards)
print(f"๐ Shuffled Cards: {cards}")
The random module is designed for simulations, games, and modeling โ NOT for cryptographic tokens or password generation. For cryptographically secure randomness, always use secrets.token_hex() or secrets.randbelow().
The datetime module provides classes for manipulating dates, times, and intervals:
datetime.date(year, month, day): Represents a calendar date.datetime.time(hour, minute, second): Represents time of day independent of date.datetime.datetime.now(): Returns current date and time.datetime.timedelta(days, hours, minutes): Represents duration / time difference for arithmetic (e.g. adding 30 days to a date).- Formatting:
strftime(format): String Format Time (Converts datetime object to formatted string).strptime(string, format): String Parse Time (Parses raw text string into datetime object).
import datetime as dt
# 1. Current timestamp
now = dt.datetime.now()
print("Current Timestamp:", now)
# 2. Custom date formatting with strftime
formatted_date = now.strftime("%A, %d %B %Y | %I:%M:%S %p")
print("Formatted Date: ", formatted_date)
# 3. Date Arithmetic using timedelta
today = dt.date.today()
expiry_date = today + dt.timedelta(days=30)
days_remaining = (expiry_date - today).days
print(f"\nSubscription Start: {today}")
print(f"Subscription Expiry: {expiry_date} ({days_remaining} days left)")
# 4. Parsing a date string with strptime
user_input_str = "2026-12-25"
parsed_date = dt.datetime.strptime(user_input_str, "%Y-%m-%d").date()
print("Parsed Holiday Date:", parsed_date)
%Y: 4-digit Year (2026),%m: 2-digit Month (01-12),%d: Day of month (01-31).%H: 24-hour clock (00-23),%I: 12-hour clock (01-12),%p: AM/PM.%A: Full weekday name (Monday),%B: Full month name (August).
The statistics module provides built-in functions for calculating mathematical statistics of numeric datasets without needing heavy third-party libraries like NumPy for basic tasks:
mean(data): Arithmetic mean (average).median(data): Middle value (robust against extreme outliers).mode(data): Most frequently occurring value.stdev(data): Sample standard deviation (measures variance spread).quantiles(data, n=4): Divides dataset into $n$ continuous intervals (quartiles).
import statistics as stats
exam_scores = [78, 85, 92, 85, 99, 64, 85, 90, 72, 88]
avg_score = stats.mean(exam_scores)
median_score = stats.median(exam_scores)
most_common = stats.mode(exam_scores)
spread = stats.stdev(exam_scores)
print("Dataset:", exam_scores)
print("=" * 40)
print(f"โข Mean (Average): {avg_score:.2f}")
print(f"โข Median (Midpoint): {median_score}")
print(f"โข Mode (Most Common): {most_common}")
print(f"โข Standard Deviation: {spread:.2f}")
When analyzing real-world metrics like salaries or home prices where extreme outliers skew results, median() provides a much more accurate picture than mean().
The random module uses the Mersenne Twister PRNG, which is completely predictable after observing 624 generated outputs. Never use random for security tokens, passwords, or encryption keys โ use the standard library "secrets" module instead.
Write a program to generate a 6-digit random OTP (One Time Password) and calculate the expiry timestamp 5 minutes from now using datetime.timedelta.
import random
import datetime as dt
otp = random.randint(100000, 999999)
now = dt.datetime.now()
expiry = now + dt.timedelta(minutes=5)
print(f"๐ Your One-Time Password (OTP): {otp}")
print(f"โณ Generated At: {now.strftime('%H:%M:%S')}")
print(f"โ Valid Until: {expiry.strftime('%H:%M:%S')} (5 mins expiry)")
Q What is the difference between random.choice() and random.choices()?
random.choice(seq) returns a single random element. random.choices(seq, k=n) returns a list of n elements chosen with replacement (duplicates possible).
Q How can I make randomized test results reproducible across team members?
Set a constant seed using random.seed(42) at the start of your script. This forces the PRNG to produce identical outputs on every run.
Q What is the difference between date, time, and datetime in Python?
date represents calendar date (year/month/day). time represents clock time (hour/min/sec). datetime combines both into a single unified timestamp.