Standard Library
Learn how to use Python's most useful built-in modules — os, sys, math, datetime, random, and json.
Standard Library
Python comes with a huge collection of built-in modules called the standard library. These are installed with Python — no pip needed. They cover file system operations, math, dates, randomness, JSON, and much more.
This file covers the modules you will use in almost every real project.
math — mathematical operations
import mathprint(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
print(math.sqrt(144)) # 12.0 — square root
print(math.pow(2, 10)) # 1024.0 — power
print(math.floor(3.9)) # 3 — round down
print(math.ceil(3.1)) # 4 — round up
print(math.abs(-5)) # use built-in abs() instead
print(math.factorial(5)) # 120 — 5!
print(math.log(100, 10)) # 2.0 — log base 10
print(math.log2(1024)) # 10.0 — log base 2Trigonometry:
print(math.sin(math.pi / 2)) # 1.0
print(math.cos(0)) # 1.0
print(math.degrees(math.pi)) # 180.0 — radians to degrees
print(math.radians(180)) # 3.14... — degrees to radiansUseful constants and checks:
print(math.inf) # inf — positive infinity
print(math.isinf(math.inf)) # True
print(math.isnan(float('nan'))) # True — check for not-a-numberrandom — generating random values
import randomRandom numbers:
print(random.random()) # float between 0.0 and 1.0
print(random.uniform(1, 10)) # float between 1 and 10
print(random.randint(1, 100)) # integer between 1 and 100 inclusive
print(random.randrange(0, 100, 5)) # random from 0,5,10,...,95Random choices from a sequence:
fruits = ["apple", "banana", "mango", "orange"]
print(random.choice(fruits)) # one random item
print(random.choices(fruits, k=3)) # 3 random items with repetition
print(random.sample(fruits, k=3)) # 3 random items without repetitionShuffling:
cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random.shuffle(cards)
print(cards) # [7, 2, 9, 1, 5, ...] — shuffled in placeSeeding — reproducible randomness:
random.seed(42)
print(random.randint(1, 100)) # always the same number with seed 42
print(random.randint(1, 100)) # always the same second numberSeeding is useful for testing — same seed always produces the same sequence of random values.
random is not cryptographically secure. Never use it for passwords, tokens, or security-sensitive code. Use Python's secrets module for that instead:
import secrets
print(secrets.randbelow(100)) # cryptographically secure random int
print(secrets.token_hex(16)) # secure random hex string
print(secrets.token_urlsafe(16)) # secure random URL-safe stringdatetime — working with dates and times
from datetime import datetime, date, time, timedeltaToday's date and current time:
today = date.today()
print(today) # 2026-06-02
now = datetime.now()
print(now) # 2026-06-02 14:35:22.123456Creating specific dates:
birthday = date(1999, 3, 15)
print(birthday) # 1999-03-15
print(birthday.year) # 1999
print(birthday.month) # 3
print(birthday.day) # 15Creating specific datetimes:
meeting = datetime(2026, 6, 15, 9, 30, 0)
print(meeting) # 2026-06-15 09:30:00timedelta — differences and arithmetic:
today = date.today()
one_week = timedelta(weeks=1)
ten_days = timedelta(days=10)
print(today + one_week) # 7 days from now
print(today - ten_days) # 10 days ago
# difference between two dates
start = date(2026, 1, 1)
end = date(2026, 6, 2)
diff = end - start
print(diff.days) # 152Formatting dates — strftime:
now = datetime.now()
print(now.strftime("%Y-%m-%d")) # 2026-06-02
print(now.strftime("%d/%m/%Y")) # 02/06/2026
print(now.strftime("%B %d, %Y")) # June 02, 2026
print(now.strftime("%I:%M %p")) # 02:35 PM
print(now.strftime("%A, %B %d, %Y")) # Tuesday, June 02, 2026Common format codes:
| Code | Meaning | Example |
|---|---|---|
%Y | 4-digit year | 2026 |
%m | Month as number | 06 |
%d | Day as number | 02 |
%B | Full month name | June |
%A | Full weekday name | Tuesday |
%H | Hour 24h | 14 |
%I | Hour 12h | 02 |
%M | Minutes | 35 |
%p | AM or PM | PM |
Parsing a string into a date — strptime:
date_string = "02/06/2026"
parsed = datetime.strptime(date_string, "%d/%m/%Y")
print(parsed) # 2026-06-02 00:00:00
print(parsed.year) # 2026os — interacting with the operating system
import osCurrent directory:
print(os.getcwd()) # /home/ali/projects
os.chdir("/home/ali") # change directoryListing files:
files = os.listdir(".") # list current directory
print(files) # ['main.py', 'utils.py', 'data.json']Path operations:
print(os.path.exists("main.py")) # True or False
print(os.path.isfile("main.py")) # True
print(os.path.isdir("my_folder")) # True or False
print(os.path.join("home", "ali", "file.txt")) # home/ali/file.txt
print(os.path.basename("/home/ali/file.txt")) # file.txt
print(os.path.dirname("/home/ali/file.txt")) # /home/ali
print(os.path.splitext("report.pdf")) # ('report', '.pdf')Creating and removing directories:
os.mkdir("new_folder") # create one folder
os.makedirs("a/b/c") # create nested folders
os.rmdir("new_folder") # remove empty folderEnvironment variables:
home = os.environ.get("HOME", "not set")
print(home) # /home/ali
# set one for this session
os.environ["MY_VAR"] = "hello"Running shell commands:
os.system("ls -la") # runs a shell commandFor modern path handling, prefer pathlib over os.path. It is more readable and object-oriented. We cover it in the File Handling section.
sys — system-specific information
import sysprint(sys.version) # Python version string
print(sys.platform) # 'linux', 'darwin', 'win32'
print(sys.executable) # path to the Python interpreterCommand line arguments:
# run as: python3 script.py Ali 22
print(sys.argv) # ['script.py', 'Ali', '22']
print(sys.argv[0]) # script.py — the script name
print(sys.argv[1]) # Ali — first argumentExiting the program:
if len(sys.argv) < 2:
print("Usage: python3 script.py <name>")
sys.exit(1) # exit with error code 1Standard streams:
sys.stdout.write("Hello\n") # same as print()
sys.stderr.write("Error!\n") # write to error streamjson — working with JSON data
JSON is the most common format for sending and receiving data on the web. Python's json module makes it easy to work with.
import jsonPython dict → JSON string (serializing):
person = {
"name": "Ali",
"age": 22,
"city": "Lahore",
"skills": ["Python", "JavaScript"],
"active": True
}
json_string = json.dumps(person)
print(json_string)
# {"name": "Ali", "age": 22, "city": "Lahore", "skills": ["Python", "JavaScript"], "active": true}
# pretty printed
json_pretty = json.dumps(person, indent=4)
print(json_pretty)Output:
{
"name": "Ali",
"age": 22,
"city": "Lahore",
"skills": [
"Python",
"JavaScript"
],
"active": true
}JSON string → Python dict (deserializing):
json_string = '{"name": "Ali", "age": 22, "active": true}'
person = json.loads(json_string)
print(person["name"]) # Ali
print(person["active"]) # True — JSON true becomes Python True
print(type(person)) # <class 'dict'>JSON type mapping:
| JSON | Python |
|---|---|
string | str |
number | int or float |
true / false | True / False |
null | None |
array | list |
object | dict |
Reading and writing JSON files:
# write to file
with open("data.json", "w") as f:
json.dump(person, f, indent=4)
# read from file
with open("data.json", "r") as f:
data = json.load(f)
print(data["name"]) # Alijson.dump() and json.load() work with files. json.dumps() and json.loads() work with strings. The s stands for string.
A real example — putting it together
A simple program that generates a daily report and saves it as JSON:
import json
import random
from datetime import datetime
def generate_report(team):
report = {
"generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"team": team,
"members": []
}
names = ["Ali", "Sara", "Omar", "Fatima", "Zainab"]
for name in names:
report["members"].append({
"name": name,
"tasks_completed": random.randint(3, 12),
"hours_logged": round(random.uniform(5, 9), 1)
})
return report
report = generate_report("Backend")
# save to file
with open("report.json", "w") as f:
json.dump(report, f, indent=4)
# print summary
print(f"Report for: {report['team']} team")
print(f"Generated: {report['generated_at']}")
print(f"Members: {len(report['members'])}")
total_tasks = sum(m["tasks_completed"] for m in report["members"])
print(f"Total tasks completed: {total_tasks}")Summary
| Module | Use for |
|---|---|
math | Math functions, constants, trigonometry |
random | Random numbers, choices, shuffling |
secrets | Cryptographically secure random values |
datetime | Dates, times, formatting, arithmetic |
os | File system, paths, environment variables |
sys | Python info, command line args, exit |
json | Read and write JSON data |