10xdev Book: Programming from Zero to Pro with Python

Chapter 11: Python 3.14's Standard Library – Your Built-In Toolkit

Chapter Introduction

You’ve learned to structure your own code using functions and classes (OOP). That’s awesome! But one of Python’s biggest strengths is its philosophy of “batteries included.” This means Python comes bundled with a vast collection of pre-written code, ready for you to use, called the Standard Library.

Think of it like getting a huge, high-quality toolbox for free when you get Python. Need to do complex math? There’s a math toolbox. Need to generate random numbers? Grab the random toolbox. Need to work with dates and times? Use the datetime toolbox.

These “toolboxes” are called modules. Learning how to import and use modules from the standard library saves you tons of time and effort because you don’t have to reinvent the wheel for common tasks. Let’s explore some of the most useful tools Python 3.14 gives you right out of the box.


1. What’s a Module and How Do We Use It?

A module is simply a Python file (.py) containing reusable code – functions, classes, and variables – written by the Python developers.

Bringing in the Tools: import

To use a module, you must first import it, usually at the top of your script.

# Import the entire 'math' module
import math

# Use functions/constants via module_name.item_name
pi_value: float = math.pi
sqrt_of_9: float = math.sqrt(9)

print(f"Value of Pi: {pi_value}")
print(f"Square root of 9: {sqrt_of_9}")

Prefixing with math. keeps things organized and avoids naming conflicts.


Other Ways to Import

  • Import Specific Items (from ... import ...): Grab only what you need.
    from math import pi, sqrt # Import only pi and sqrt
    
    print(f"Pi directly: {pi}")
    print(f"Sqrt of 16: {sqrt(16)}") # Use them without the 'math.' prefix
    

    Use this carefully; importing too many names directly can make it unclear where they came from.

  • Import with an Alias (import ... as ...): Give a module a shorter nickname.
    import datetime as dt # Common alias for datetime
    
    now = dt.datetime.now()
    print(f"Current moment: {now}")
    

    Very common practice (e.g., import pandas as pd).


2. Discovering What’s Inside (dir() and help())

You can’t memorize everything! Learn to explore:

  • dir(module): Lists all names (functions, variables, etc.) inside a module.
  • help(module.item): Shows the documentation (docstring) for a specific function, class, or the module itself.
import random

# See what's available in 'random' (long list!)
# print(dir(random))

# Get help specifically for the 'randint' function
help(random.randint)
# Output explains it returns a random integer between a and b, inclusive.

3. Key Standard Library Modules in Python 3.14

Let’s look at some indispensable modules:

A. math: Advanced Math Functions 📐

For trigonometry, logarithms, square roots, etc.

import math

print(f"Square root of 81: {math.sqrt(81)}")      # -> 9.0
print(f"3 to the power of 4: {math.pow(3, 4)}")    # -> 81.0
print(f"Ceiling of 5.1: {math.ceil(5.1)}")     # -> 6 (rounds up)
print(f"Floor of 5.9: {math.floor(5.9)}")     # -> 5 (rounds down)
print(f"Value of Pi: {math.pi}")
print(f"Value of Euler's number (e): {math.e}")

B. random: Generating Randomness 🎲

Crucial for games, simulations, shuffling data, or picking random samples.

import random

# Random integer within a range (inclusive)
dice_roll: int = random.randint(1, 6)
print(f"Dice roll: {dice_roll}")

# Random float between 0.0 (inclusive) and 1.0 (exclusive)
rand_float: float = random.random()
print(f"Random float [0,1): {rand_float}")

# Pick a random element from a list
names: list[str] = ["Alice", "Bob", "Charlie", "Diana"]
winner: str = random.choice(names)
print(f"Randomly chosen winner: {winner}")

# Shuffle a list in-place (modifies the original list)
deck: list[str] = ["A", "K", "Q", "J"]
random.shuffle(deck)
print(f"Shuffled deck: {deck}")

C. datetime: Handling Dates and Times ⏰

Essential for logging, scheduling, calculating durations, or anything time-related.

import datetime as dt

# Get current date and time
now: dt.datetime = dt.datetime.now()
print(f"Now: {now}")

# Get just today's date
today: dt.date = dt.date.today()
print(f"Today: {today}")

# Create a specific date
specific_date: dt.date = dt.date(2025, 12, 25)
print(f"Specific date: {specific_date}")

# Format dates/times into strings (strftime)
formatted_now: str = now.strftime("%Y-%m-%d %H:%M:%S") # YYYY-MM-DD HH:MM:SS
print(f"Formatted: {formatted_now}")

# Parse strings into datetime objects (strptime)
date_str = "2025-10-31"
halloween: dt.date = dt.datetime.strptime(date_str, "%Y-%m-%d").date()
print(f"Parsed date: {halloween}")

# Time differences (timedelta)
one_day = dt.timedelta(days=1)
tomorrow = today + one_day
print(f"Tomorrow: {tomorrow}")

# Python 3.14+ Note: datetime.time objects also gain strptime/strftime
specific_time = dt.time(14, 30) # 2:30 PM
print(f"Formatted time: {specific_time.strftime('%I:%M %p')}") # -> 02:30 PM

D. os and pathlib: Interacting with the OS 📁

These modules let you work with files, directories, paths, and environment variables. pathlib is the modern, preferred way to handle paths.

import os
from pathlib import Path

# --- Using pathlib (Recommended) ---
# Get current working directory as a Path object
cwd: Path = Path.cwd()
print(f"Current Directory (pathlib): {cwd}")

# Create paths using the / operator (works cross-platform)
data_folder: Path = cwd / "my_data"
report_file: Path = data_folder / "report_2025.txt"
print(f"Report file path: {report_file}")

# Check existence
print(f"Does data folder exist? {data_folder.exists()}")

# Create directories
data_folder.mkdir(parents=True, exist_ok=True) # Create 'my_data' if needed
print(f"Ensured {data_folder} exists.")

# List directory contents
print("\nFiles in current directory:")
for item in cwd.iterdir():
    if item.is_file():
        print(f"- {item.name}")

# Python 3.14+ Note: pathlib gets recursive copy/move methods
# e.g., source_dir.copytree(destination_dir)

# --- Using os (Older style, still useful for some things) ---
# Get an environment variable
home_dir_os: str | None = os.getenv("HOME") # Or "USERPROFILE" on Windows
print(f"Home directory (os.getenv): {home_dir_os}")

# os.path is the older way to manipulate paths (less intuitive than pathlib)
old_style_path = os.path.join(os.getcwd(), "old_file.txt")
print(f"Old style path joining: {old_style_path}")

E. (New in 3.14 Context) compression: Unified Compression Tools Zstd Included!

Python 3.14 tidies up access to various compression libraries (gzip, bz2, lzma) under a single compression module and adds built-in support for the fast Zstandard (zstd) algorithm.

import compression
import zstandard # Often still imported directly if using zstd features

# Example: Compressing data with zstd (concept)
data_to_compress: bytes = b"This is some data that needs compressing. " * 100
try:
    # Use the unified interface or zstd directly
    compressed_data: bytes = zstandard.compress(data_to_compress)
    print(f"Original size: {len(data_to_compress)}, Compressed size (zstd): {len(compressed_data)}")

    decompressed_data: bytes = zstandard.decompress(compressed_data)
    # print(f"Decompressed successfully: {decompressed_data == data_to_compress}")

    # You could also potentially use compression.zstd.compress etc.
except ImportError:
    print("Note: Direct 'zstandard' import might require separate installation if not fully bundled.")
except Exception as e:
    print(f"Compression error: {e}")

Having zstandard built-in is great for performance, offering fast compression and good ratios.


4. Applied Project: Number Guessing Game (Refined)

Let’s refine the guessing game using what we know.

# --- Number Guessing Game (Refined) ---

import random
import sys # To exit cleanly

def play_guessing_game(lower_bound: int = 1, upper_bound: int = 100):
    """Plays a number guessing game with the user."""
    secret_number: int = random.randint(lower_bound, upper_bound)
    attempts: int = 0

    print(f"I've picked a secret number between {lower_bound} and {upper_bound}. Can you guess it?")
    print("--- Game Start ---")

    while True:
        try:
            user_guess_str: str = input("Enter your guess (or type 'quit'): ").strip().lower()

            if user_guess_str == 'quit':
                print(f"Quitting the game. The number was {secret_number}.")
                break # Exit the loop

            user_guess: int = int(user_guess_str)
            attempts += 1

            if not lower_bound <= user_guess <= upper_bound:
                 print(f"Please guess a number between {lower_bound} and {upper_bound}.")
                 continue # Skip to next attempt

            if user_guess < secret_number:
                print("Too low! Try a higher number.")
            elif user_guess > secret_number:
                print("Too high! Try a lower number.")
            else:
                print(f"🎉 Congratulations! You guessed it in {attempts} attempts. The number was {secret_number}.")
                break # Exit the loop

        except ValueError:
            print("Invalid input. Please enter a whole number or 'quit'.")

# Run the game if this script is executed directly
if __name__ == "__main__":
    play_guessing_game()

5. Chapter Summary

  • Python’s Standard Library (“batteries included”) provides numerous modules for common tasks.
  • Use import module, from module import item, or import module as alias to access them.
  • Explore modules with dir() and help().
  • Key modules include math, random, datetime, os, and especially the modern pathlib for file paths.
  • Python 3.14 improves access to compression tools via the compression module, including zstandard.

The standard library covers many bases, but the Python ecosystem’s true power comes from the vast universe of external libraries developed by the community. Next, we’ll learn how to manage these external packages professionally using uv and virtual environments.