Kahibaro
Discord Login Register

Standard libraries

Why the Standard Library Matters

Python comes with a “batteries included” philosophy. That means when you install Python, you automatically get a large collection of ready‑made modules called the standard library.

You don’t need to install these with pip. They are already there, waiting to be imported with import.

In this chapter you will:

This is about getting comfortable exploring and using what’s already built into Python.


What Is the Standard Library?

The standard library is a collection of modules that:

Some modules are tiny helpers, others are large toolkits. You import them like any other module, for example:

import math          # math functions
import random        # randomness
import datetime      # dates and times
import os            # operating system utilities
import json          # JSON data

You’ll learn specific modules over time. The important habit is: before writing a lot of code, ask “Is there a standard library module for this?”


Finding and Exploring Standard Library Modules

You don’t need to memorize the whole library. You just need to know how to look things up.

Official documentation

The official reference is:

There you’ll find a big list of modules, grouped by topic. A few common groups:

You don’t need to read it all; you search it when needed.

Getting help inside Python

You can ask Python itself about modules, functions, and classes.

import math
help(math)          # overview of math module
help(math.sqrt)     # info about a specific function

This is useful when:

How to Import and Use Standard Library Modules

You’ve already seen import in the parent chapter. Here we’ll focus on common patterns that appear a lot with standard library modules.

1. Import the whole module

import math
result = math.sqrt(16)

You must use the module name (math) as a prefix.

2. Import with an alias

Shorten long names with as:

import datetime as dt
today = dt.date.today()

This is common for modules with longer names.

3. Import specific names

from math import sqrt, pi
length = sqrt(25)
circumference = 2 * pi * 3

You can then use sqrt and pi directly, without math..

For beginners, it’s often clearer to use full imports (import math), because you always see where a function came from.


Commonly Useful Standard Library Modules (Beginner-Friendly)

Here are some standard library modules that are especially helpful when you’re starting out. Each one includes a simple example to show how it might be used.

You don’t need to master all of them now — treat this as a “toolbox preview”.

`os`: Working with the Operating System

os helps you interact with the system: environment variables, directories, paths, and more.

Common beginner uses:

import os
print("Current directory:", os.getcwd())
print("Files here:", os.listdir())   # list of names in current directory

`pathlib`: Modern File Paths

pathlib provides an object-oriented way to work with file paths. It’s often nicer than manually joining strings.

from pathlib import Path
current = Path.cwd()
print("Current directory:", current)
notes = current / "notes.txt"  # build a path safely
print("Will use file:", notes)

You’ll often see pathlib and os used together when working with files.

`sys`: System-specific Information

sys gives access to things like command-line arguments and the Python version.

Simple use: show which version of Python is running.

import sys
print("Python version:", sys.version)

Later, you might use sys.argv to read command-line arguments for scripts.

`time`: Simple Time Operations

time deals with time in seconds. It’s often used for:

import time
print("Waiting for 2 seconds...")
time.sleep(2)   # pause the program for 2 seconds
print("Done!")

For dates and calendars, you’ll usually prefer datetime, which gets its own chapter.

`random`: Randomness

random helps you pick random numbers or choices. It’s great for games and simple simulations.

Example: pick a random item from a list.

import random
colors = ["red", "green", "blue"]
choice = random.choice(colors)
print("Random color:", choice)

You’ll see more detail in the dedicated random section.

`math`: Math Functions

math provides mathematical functions: square roots, trigonometry, constants like $ \pi $.

Very common for any numeric work:

import math
print("Square root of 9:", math.sqrt(9))
print("Pi:", math.pi)

You’ll explore math more in its own section.

`datetime`: Dates and Times

datetime is for working with dates, times, and time differences.

Example: get today’s date.

import datetime
today = datetime.date.today()
print("Today is:", today)

You’ll learn more about datetime later in this chapter group.


Handling Data Formats: `json` and `csv`

Many programs read and write data. Two very common formats have built-in support.

`json`: JavaScript Object Notation

JSON is a common text format for structured data. json can:

Python → JSON string

import json
data = {"name": "Alice", "age": 30, "languages": ["Python", "JavaScript"]}
json_text = json.dumps(data)
print(json_text)  # a JSON-formatted string

JSON string → Python

import json
json_text = '{"name": "Bob", "age": 25}'
data = json.loads(json_text)
print(data["name"])  # Bob

Later, you might combine json with file handling to save and load data from files.

`csv`: Comma-Separated Values

csv helps work with table-like data in .csv files (like spreadsheets exported to text).

Here’s a very small example of writing rows to a CSV file:

import csv
rows = [
    ["name", "score"],
    ["Alice", 95],
    ["Bob", 88],
]
with open("scores.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(rows)

And reading them back:

import csv
with open("scores.csv", "r", newline="") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

Text and String Helper Modules

Sometimes str methods are enough; sometimes you want extra tools from the standard library.

`string`: Predefined Character Sets

string provides useful constants:

import string
print(string.ascii_letters)  # all A–Z and a–z
print(string.digits)         # 0123456789
print(string.punctuation)    # punctuation characters

You might combine this with random to build a password generator (like in the projects chapter).

`textwrap`: Wrapping and Indenting Text

textwrap helps format long text neatly.

Example: wrap text to a fixed width:

import textwrap
text = "Python is a powerful, easy-to-learn programming language."
wrapped = textwrap.fill(text, width=20)
print(wrapped)

Collections and Iteration Helpers

These modules help you work with lists, counters, and loops in more powerful ways.

`collections`: Specialized Data Containers

collections offers useful container types. One very handy one is Counter for counting things.

from collections import Counter
letters = ["a", "b", "a", "c", "b", "a"]
counts = Counter(letters)
print(counts)         # Counter({'a': 3, 'b': 2, 'c': 1})
print(counts["a"])    # 3

You can use this to count words, characters, responses in a quiz, etc.

`itertools`: Extra Tools for Loops

itertools provides helpers for building advanced loops. Even beginners can use a few simple ones.

Example: create an infinite counter (be careful to stop it!)

import itertools
for i in itertools.count(start=1):
    print(i)
    if i == 5:
        break

This prints 1 to 5 and then stops.


Debugging and Logging Helpers

When programs grow, it’s useful to see what’s happening inside.

`logging`: Simple Logging

logging lets you record information about what your program is doing. Unlike print, you can control the level of importance and send it to files.

Very simple setup:

import logging
logging.basicConfig(level=logging.INFO)
logging.info("Program started")
name = "Alice"
logging.debug(f"Name is {name}")   # will not show with level=INFO
logging.warning("Something might be wrong")

You can start by just using print when you are new, then gradually learn logging as your programs get more complex.

`traceback`: Working with Error Traces

traceback lets you capture or format the error trace (the message Python shows when an exception occurs). This is more advanced and often combined with try/except, which you’ll see in the errors chapter.


When to Use the Standard Library vs External Libraries

The standard library is your first stop:

You use pip to install external libraries only when:

Examples:

Practicing with the Standard Library

Here are some small practice ideas that focus on using built-in modules:

  1. File lister
    • Use os or pathlib to list all files in the current directory.
    • Print only files that end with .txt.
  2. Simple timer
    • Use time to measure how long it takes a loop to run.
    • Print the elapsed time.
  3. Word counter
    • Take a short text (as a string).
    • Split it into words.
    • Use collections.Counter to count how many times each word appears.
  4. Random password
    • Use string (letters, digits, punctuation) and random to generate a random password of a given length.

As you work on projects in later chapters, try to ask yourself:

“Is there a standard library module that would make this easier?”

The more often you look, the more comfortable you’ll become with this powerful toolbox.

Views: 20

Comments

Please login to add a comment.

Don't have an account? Register now!