An import statement makes a module’s code available to a Python program. Modules group code for particular purposes, so importing one extends Python beyond its core features without requiring knowledge of its internal implementation. section 5.1.5
Use imports to:
- Load a built-in module, such as os, string, csv, or zipfile. section 5.1.5
- Use an installed external module, such as PyPDF2, matplotlib, pandas, or PyMuPDF. section 5.1.5 section 9.4.2
- Make names such as os.listdir, string.punctuation, and zipfile.ZipFile available to program code. section 3.3.2 section 9.4.2 section 5.1.5
Fixing a missing import
A password checker that uses string.punctuation fails with NameError when string has not been imported. Adding import string at the start makes the punctuation test work: passwords without punctuation return False, while 'N3w Y0rk J375$' returns True. section 3.3.2
Importing modules for a PDF tool
A PDF-cover utility calls os.listdir and os.path.join, so it needs import os. It also imports a PDF library. When PyPDF2 3.0.0 rejects the older PdfFileReader name, the code must use PdfReader, install an older compatible version, or switch to PyMuPDF. section 9.4.2
Table 5.2 Summary of commonly used Python modules
|
Module
|
Built-In
|
Description
|
|---|---|---|
|
csv
|
Yes
|
Aids in the reading, writing, and analysis of CSV files
|
|
zipfile
|
Yes
|
Aids in the creation and extraction of compressed zip archive files
|
|
matplotlib
|
No
|
Graphics library for plotting that serves as the basis of other graphics libraries and can offer high levels of customization
|
|
plotly
|
No
|
A graphics library used for creating interactive plots for the web
|
|
seaborn
|
No
|
A graphics library built on top of matplotlib that aids in creating high- quality plots more easily than matplotlib
|
|
pandas
|
No
|
A data processing library that specializes in data frames, which are analogous to spreadsheets
|
|
scikit-learn
|
No
|
Contains basic tools for machine learning (i.e., helping to learn from data and make predictions)
|
|
numpy
|
No
|
Offers highly efficient data processing
|
|
pygame
|
No
|
A game programming library that helps to build interactive, graphical games in Python
|
|
django
|
No
|
Web development library that aids in designing websites and web applications
|
Browse a compact comparison of built-in and external Python modules and the tasks they support. section 5.1.5












