Chapter 9 of 11
Using Python’s Built-in Superpowers: Modules and the Standard Library
Instead of reinventing the wheel, tap into Python’s huge toolbox of ready-made features for random numbers, dates, math, and more. You’ll discover how a single import can unlock powerful capabilities in just a few lines of code.
Why Python Has Built-in Superpowers
Python's Toolbox
Python includes a huge toolbox of ready-made code called the standard library. You can import these tools instead of writing everything from scratch.
What Is a Module?
A module is a Python file that contains code: functions, classes, and variables. The standard library is a big collection of modules that comes with Python.
Why Import?
An import statement is like asking Python: "Bring me this toolbox so I can use its tools." You place imports at the top of your file.
What You Will Learn
You will learn two import styles, use `math`, `random`, `datetime`, `pathlib`, see what `pip` is, and practice reading docs and adapting examples.
The Two Main Import Styles
Two Import Styles
Python has two common import styles: `import module` and `from module import name`. Both let you use tools from a module in your code.
`import module`
With `import math`, you use functions with the module name as a prefix, like `math.cos` or `math.pi`. This style is very clear and beginner-friendly.
`from module import name`
With `from math import cos, pi`, you can call `cos` and `pi` directly, without `math.`. It is shorter but can be less clear if you import many names.
Which Style to Use?
As a beginner, prefer `import module` for clarity. Use `from module import name` when you often use a few tools from a module and want shorter code.
Try It: Your First Imports
Run this code and observe the output. Then change some values and run it again.
Beginner-Friendly Module: math
Meet the math Module
The `math` module provides constants like `math.pi` and functions like `math.sqrt`. It is great for more advanced calculations than basic `+ - * /`.
Useful math Tools
Common tools: `math.pi`, `math.e`, `math.sqrt(x)`, `math.ceil(x)`, `math.floor(x)`. They help with roots and rounding up or down.
Example: Movie Night
Use `math.ceil(people / seatsperrow)` to find how many full rows of seats you need. You cannot seat people in half a row, so you round up.
Beginner-Friendly Module: random
Meet the random Module
The `random` module lets programs make random choices: roll dice, shuffle lists, and pick random items. Great for games and simulations.
Useful random Tools
`random.random()` gives a float from 0.0 to 1.0. `random.randint(a, b)` gives an integer from a to b. `random.choice(list)` picks a random item.
Example: Dice and Snacks
Use `random.randint(1, 6)` to roll dice, and `random.choice(snacks)` to pick a random snack from a list. Each run can give different results.
Working with Dates and Paths: datetime and pathlib
Meet datetime
The `datetime` module helps you work with dates and times. You can get today’s date, the current time, and do math with dates safely.
datetime Example
Use `date.today()` for today’s date and `datetime.now()` for date plus time. You can subtract dates to get differences in days.
Meet pathlib
`pathlib` helps you build and inspect file paths that work across Windows, macOS, and Linux. It is safer than writing raw strings.
pathlib Example
Use `Path.cwd()` for the current folder, then build paths like `current / "notes.txt"`. The `/` operator joins path parts.
Activity: Pick the Right Module
For each situation, decide which standard library module (`math`, `random`, `datetime`, `pathlib`) you would reach for first. Think before you peek at the hints.
- You want to simulate flipping a coin 100 times.
- Which module? Why?
- You want to find how many days are left until the last day of this year.
- Which module? Why?
- You want to calculate the length of the diagonal of a rectangle given its width and height.
- Which module? Why?
- You want to save a game score to a file called `scores.txt` in a `data` folder next to your script. You need to build that file path.
- Which module? Why?
Hints (unfold in your mind, not in code):
- Random choices or numbers? Think `random`.
- Real-world dates and times? Think `datetime`.
- Extra math formulas (like square root)? Think `math`.
- File and folder locations? Think `pathlib`.
After you decide, write a short comment in your own words: "I would use X because..." for each case.
What Is pip and When Do You Need It?
Standard Library vs Extras
The standard library comes with Python. Third-party packages are extras made by others. You need a tool named `pip` to install those extras.
What pip Does
`pip` is Python’s package manager. It downloads and installs packages from PyPI so you can `import` them in your programs.
Example pip Commands
In a terminal you might run `pip install requests` or `pip install numpy`. For this course, you just need to know what pip is, not use it deeply.
Quick Check: Imports and pip
Test your understanding of import styles and pip.
Which statement about Python modules and pip is MOST accurate for you as a beginner?
- I must use pip to install the math and random modules before I can import them.
- Standard library modules like math and random work without pip, but I use pip to install extra third-party packages.
- I should always use from module import name and never use import module.
Show Answer
Answer: B) Standard library modules like math and random work without pip, but I use pip to install extra third-party packages.
Standard library modules such as math, random, datetime, and pathlib come bundled with Python, so you can import them without pip. pip is used to install third-party packages from outside the standard library. Both import styles are valid; as a beginner, import module is often clearer.
Mini-Project: A Tiny Daily Helper Script
Combine several modules to build a tiny script. Plan it first, then code.
Goal: A script that:
- Shows today’s date.
- Suggests a random activity.
- Saves a short log entry to a file.
Step 1: Plan the modules
- Which module gives you today’s date? (Hint: `datetime`)
- Which module gives random choices? (Hint: `random`)
- Which module helps with file paths? (Hint: `pathlib`)
Step 2: Sketch the code (pseudocode)
- Import the modules you need.
- Get today’s date.
- Pick a random activity from a list, like `["read", "exercise", "draw", "code"]`.
- Print a friendly message using the date and activity.
- Build a path to a file called `daily_log.txt` in the current folder.
- Append a line like `2026-04-04: activity` to the file.
Step 3: Turn pseudocode into real Python
Try to write the real code yourself. If you get stuck, look back at the earlier examples for `datetime`, `random`, and `pathlib` and adapt them.
Review: Key Terms
Flip these cards in your mind or with a partner. Say the answer out loud before you check it.
- Module
- A Python file that contains code (functions, classes, variables) that you can import and reuse in other programs.
- Standard library
- The collection of modules that comes built into Python (such as math, random, datetime, pathlib). You do not need pip to use them.
- import module
- An import style that brings in the whole module, so you use names with a prefix, like math.sqrt or random.randint.
- from module import name
- An import style that brings specific names from a module so you can use them directly, like from math import sqrt, pi.
- pip
- Python’s package manager. It installs third-party packages from the Python Package Index (PyPI) so you can import them.
- pathlib
- A standard library module for working with file and folder paths in a clean, cross-platform way using Path objects.
Key Terms
- pip
- Python’s package manager used to install third-party packages from the Python Package Index (PyPI).
- module
- A Python file containing code (functions, classes, variables) that can be imported and reused.
- pathlib
- A standard library module that provides an object-oriented way to work with file system paths.
- datetime
- A standard library module for working with dates and times.
- import statement
- A line of code that tells Python to load a module or specific names from a module.
- standard library
- The set of modules that comes built into Python, available without separate installation.