Python: Standard Library Basics (Part 1)
Last updated: 2026-09-22
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 ⭐)
▶ Try it YourselfOutput:
# Executed successfully
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 ⭐)
▶ Try it YourselfOutput:
\r⏰ Time
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 ⭐⭐)
▶ Try it YourselfOutput:
Usage: python calculator.py num1 operator num2
Example: python calculator.py 3 + 5
Error: cannot divide by zero
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 ⭐⭐)
▶ Try it YourselfOutput:
Batch rename example (display only, not executed):
Iterate all .txt files, rename to prefix_001.txt format
5. 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.time.sleep() blocks the entire program. How do I do a non-blocking delay?sleep() does block the current thread. For non-blocking delays, use multi-threading or async frameworks like asyncio. For simple scenarios, sleep() is sufficient.os or pathlib?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.