Python Intermediate: Objects, Errors and Files
The Standard Library
In this lesson you will
- Import modules in several ways
- Use math, random, statistics and datetime
- Use Counter, defaultdict, deque and itertools
Introduction
Python is famous for being "batteries included". Installed with the language is a large standard library: ready-made modules for maths, dates, random numbers, files, the web and much more. Before you write something yourself, check whether it is already there.
Importing
A module is a file of Python code. Use import to bring one in.
You can import specific names, or give a module a shorter name:
math and statistics
random
random makes pseudo-random numbers. Setting a seed makes the sequence repeatable, which is useful for tests.
Run it twice and you get the same answers, because of the seed. Remove the random.seed(7) line and each run will differ. random is not safe for passwords. For those, use the secrets module.
datetime
strftime formats a date as text, and strptime parses text into a date. date.today() and datetime.now() give the current time, but their output changes each time you run them.
Quick quiz
Why call random.seed(7) before generating numbers?
collections: smarter containers
Counter counts things for you:
defaultdict creates missing entries automatically, which avoids get checks:
deque is a list-like queue that is fast at both ends:
itertools
Finding more
The official documentation lists every module. Other favourites: json and csv for data, pathlib for files, re for pattern matching, argparse for command-line programs, unittest for tests, and urllib for the web. Beyond the standard library, the Python Package Index (PyPI) has hundreds of thousands of third-party packages you can install with pip.
Quick quiz
Which collections tool counts how often each item appears?
Try it yourself
Use Counter to find the three most common letters in "the quick brown fox jumps over the lazy dog", ignoring spaces. Then use datetime to print how many days there are from 2025-01-01 to 2025-12-31.
Summary
import module,from module import nameandimport module as shortbring code in.math,statistics,randomanddatetimecover numbers, chance and dates. A seed makes random repeatable.Counter,defaultdictanddequeare handy containers, anditertoolsbuilds combinations and chains.- Check the standard library, and then PyPI, before writing something yourself.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading