Skip to main content

Python Standard Library

Built-in Modules You Already Have

· 3 min read

In the previous unit, we learned how to create packages and install external libraries. Now let's explore modules that come built into Python, ready to use without installing anything.

Python Standard Library

The Standard Library

Python's standard library is a collection of modules bundled with every Python installation. These modules handle common tasks like math operations, random number generation, date manipulation, and data serialization. Let's look at four of the most useful ones.

The math Module

The math module provides mathematical functions beyond basic arithmetic.

import math

print(math.sqrt(16)) # 4.0
print(math.floor(3.7)) # 3
print(math.ceil(3.2)) # 4
print(math.pi) # 3.141592653589793

You'll find trigonometric functions (sin, cos, tan), logarithms (log, log10), and constants like pi and e. The module handles calculations that would be tedious to implement yourself.

The random Module

The random module generates random numbers and makes random selections.

import random

print(random.randint(1, 10)) # Random integer from 1 to 10
print(random.choice(['a', 'b'])) # Random element from list
print(random.random()) # Random float between 0 and 1

For shuffling a list in place, use random.shuffle(). For picking multiple unique items, use random.sample().

The datetime Module

The datetime module works with dates and times.

import datetime

today = datetime.date.today()
print(today) # 2022-04-06

now = datetime.datetime.now()
print(now.strftime("%B %d, %Y")) # April 06, 2022

You can create specific dates, calculate differences between dates, and format dates for display. The strftime method converts datetime objects into formatted strings.

The json Module

The json module converts between Python objects and JSON strings. JSON is the standard format for data exchange on the web.

import json

data = {'name': 'Alice', 'age': 25}
json_str = json.dumps(data)
print(json_str) # {"name": "Alice", "age": 25}

parsed = json.loads(json_str)
print(parsed['name']) # Alice

Use dumps (dump string) to convert Python to JSON, and loads (load string) to convert JSON back to Python.

Project: Random Shape Generator

Let's combine these modules in a Turtle program that generates random shapes:

import turtle
import random
import math
import datetime

screen = turtle.Screen()
screen.bgcolor("white")

t = turtle.Turtle()
t.speed(0)

def draw_random_shape():
sides = random.randint(3, 8)
size = random.randint(30, 80)
angle = 360 / sides

for _ in range(sides):
t.forward(size)
t.right(angle)

def draw_pattern():
for _ in range(12):
draw_random_shape()
t.right(30)
print(f"Pattern created: {datetime.date.today()}")

def clear_screen():
t.clear()

screen.onkey(draw_pattern, "p")
screen.onkey(clear_screen, "c")
screen.listen()

turtle.done()

Press "p" to draw a pattern of 12 random polygons arranged in a circle. Press "c" to clear. The program uses random to vary the shapes, math concepts for the angles, and datetime to log when each pattern was created.

The standard library has many more modules. As you encounter new problems, check the documentation to see if Python already has a solution built in.

In the next unit, we'll learn how to fetch data from the internet using APIs.