Standard Library Basics (Part 1)
One of Python's greatest features is "Batteries Included" — a full suite of standard libraries comes with every Python installation. This lesson covers four of the most commonly used modules:
random,time,sys, andos. Even learning just the most popular functions from each will help you solve many real-world problems.
1. random — Random Numbers
import random
# Random float [0, 1)
print(random.random()) # 0.3745...
# Random integer [a, b] (inclusive)
print(random.randint(1, 10)) # Random integer between 1 and 10
# Random choice
fruits = ["apple", "banana", "orange", "grape"]
print(random.choice(fruits)) # Pick one randomly
# Random sample (no replacement)
print(random.sample(fruits, 2)) # Pick 2 randomly
# Shuffle order
cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random.shuffle(cards)
print(cards) # Order is shuffled
Example: Lottery Program (Difficulty ⭐)
import random
# Lottery pool
participants = ["Alice", "Bob", "Charlie", "Diana", "Eve",
"Frank", "Grace", "Henry"]
# 1st prize — 1 winner
first = random.choice(participants)
print(f"🎉 1st Prize: {first}")
# 2nd prize — 2 winners (excluding 1st)
remaining = [p for p in participants if p != first]
second = random.sample(remaining, 2)
print(f"🎊 2nd Prize: {' & '.join(second)}")
# 3rd prize — 3 winners
remaining = [p for p in remaining if p not in second]
third = random.sample(remaining, 3)
print(f"🎁 3rd Prize: {' & '.join(third)}")
2. time — Time Handling
import time
# Current timestamp (seconds since 1970-01-01)
print(time.time()) # 1758588800.123
# Pause execution (seconds)
print("Start")
time.sleep(1) # Pause for 1 second
print("1 second later")
# Format current time
print(time.strftime("%Y-%m-%d %H:%M:%S")) # 2026-06-23 16:00:00
Example: Timer (Difficulty ⭐)
import time
def countdown(seconds):
"""Countdown timer"""
while seconds > 0:
print(f"\r⏱ {seconds} seconds left", end="")
time.sleep(1)
seconds -= 1
print("\r⏰ Time's up!")
# Measure code execution time
start = time.time()
total = sum(range(1000000))
end = time.time()
print(f"Execution time: {end - start:.4f} seconds")
3. sys — System Interaction
import sys
# Python version
print(sys.version) # 3.13.0 ...
# Command-line arguments (when running python script.py a b c)
print(sys.argv) # ['script.py', 'a', 'b', 'c']
# Exit the program
# sys.exit(0) # Normal exit
# Standard input
# line = sys.stdin.readline() # Read one line of input
Example: Command-Line Calculator (Difficulty ⭐⭐)
import sys
def main():
# Usage: python calculator.py 3 + 5
if len(sys.argv) != 4:
print("Usage: python calculator.py num1 operator num2")
print("Example: python calculator.py 3 + 5")
return
a = float(sys.argv[1])
op = sys.argv[2]
b = float(sys.argv[3])
if op == "+":
result = a + b
elif op == "-":
result = a - b
elif op == "*":
result = a * b
elif op == "/":
if b == 0:
print("Error: cannot divide by zero")
return
result = a / b
else:
print(f"Unsupported operator: {op}")
return
print(f"{a} {op} {b} = {result}")
if __name__ == "__main__":
main()
4. os — Operating System
import os
# Current working directory
print(os.getcwd()) # D:\project
# Change directory
# os.chdir("/tmp")
# List directory contents
for item in os.listdir("."):
print(item)
# Create directory
# os.mkdir("new_folder")
# Check paths
print(os.path.exists("test.txt")) # True
print(os.path.isfile("test.txt")) # True
print(os.path.isdir("data")) # True
# Join paths
path = os.path.join("data", "files", "test.txt")
print(path) # data/files/test.txt
Example: Batch File Renaming (Difficulty ⭐⭐)
import os
def batch_rename(directory, prefix):
"""Batch rename all .txt files in a directory"""
files = [f for f in os.listdir(directory) if f.endswith(".txt")]
for i, filename in enumerate(files, 1):
old_path = os.path.join(directory, filename)
new_name = f"{prefix}_{i:03d}.txt"
new_path = os.path.join(directory, new_name)
os.rename(old_path, new_path)
print(f" {filename} → {new_name}")
print("Batch rename example (display only, not executed):")
print("Iterate all .txt files, rename to prefix_001.txt format")
Common Use Cases
- random: Lottery, CAPTCHA, random test data generation, random game events.
- time: Delayed execution, performance timing, timers, scheduled tasks.
- sys: Read command-line arguments, control program exit, get Python environment info.
- os: File management, directory operations, path handling, batch renaming.
❓ FAQ
random suitable for cryptographic random numbers?random uses a PRNG (Pseudo-Random Number Generator), which is predictable. For cryptographically secure random numbers (e.g., generating passwords, tokens), use the secrets module.
Q: time.sleep() blocks the entire program. How do I do a non-blocking delay? A: sleep() does block the current thread. For non-blocking delays, use multi-threading or async frameworks like asyncio. For simple scenarios, sleep() is sufficient.
Q: Should I use os or pathlib? A: Python 3.4+ recommends pathlib (more object-oriented, more intuitive), but os is lower-level and more comprehensive. Use pathlib for new projects; use os for low-level system calls.📖 Summary
random:randint(),choice(),sample(),shuffle()— random selection and generationtime:time()timestamp,sleep()pause,strftime()formattingsys:argvcommand-line arguments,exit()program exitos: File path checks, directory operations, file renaming- These four modules are the "starter pack" for Python's standard library, used frequently in daily development
📝 Exercises
-
Basic (Difficulty ⭐): Write a program that generates 10 random integers between 1 and 100, outputs them and their average.
-
Intermediate (Difficulty ⭐⭐): Write a password generator function
generate_password(length=8)that creates random passwords containing uppercase, lowercase, and digits. Hint: Usestring.ascii_letters + string.digitsas the character pool; userandom.choice()to pick characters. -
Challenge (Difficulty ⭐⭐⭐): Write a "folder statistics tool." Given a directory path (passed via
sys.argv), count the number of files and total size for each file type (extension). Hint: Useos.listdir()to iterate,os.path.splitext()for extension,os.path.getsize()for file size.



