Lesson 27 of 30 · Files, Errors and Modules
Modules and Imports
Use ready-made code with Python's import statement. Explore math, random and datetime, learn the import styles and see how pip installs AI libraries.
- 8 min read
- Beginner
- Reviewed
- What a module is and why you rarely start from nothing
- The three ways to write an import
- Useful modules that come with Python
- How pip installs libraries such as NumPy
You do not have to write everything yourself
Need a square root? A random number? Today's date? Someone has already written and tested that code. A file of ready-made Python code is called a module, and the import statement lets you use it.
import math print(math.sqrt(144)) print(math.pi) print(math.floor(7.9))
After import math, you reach anything inside the module with a dot: math.sqrt, math.pi.
Python ships with hundreds of modules. Together they are called the standard library, and they are available as soon as Python is installed.
Three ways to import
# 1. Import the whole module import math print(math.sqrt(25)) # 2. Import only the names you need from math import sqrt, pi print(sqrt(25)) print(pi) # 3. Import with a shorter name import math as m print(m.sqrt(25))
- Style 1 is the clearest. Anyone reading
math.sqrtknows where it came from. - Style 2 saves typing when you use a few names often.
- Style 3 gives a module a short nickname. It is standard practice for data libraries, as you will see below.
random: chance and games
import random print(random.randint(1, 6)) # a whole number from 1 to 6 print(random.choice(["red", "green"])) # one item picked at random cards = [1, 2, 3, 4, 5] random.shuffle(cards) print(cards)
Run it several times. The results change.
datetime: dates and times
from datetime import date
today = date.today()
new_year = date(today.year + 1, 1, 1)
print("Today is", today)
print("Days until the new year:", (new_year - today).days)A few more worth knowing
import statistics
import json
scores = [72, 95, 61, 88]
print(statistics.mean(scores))
print(statistics.median(scores))
person = {"name": "Ada", "age": 36}
text = json.dumps(person)
print(text)
print(json.loads(text)["name"])| Module | What it is for |
|---|---|
math | Square roots, rounding, trigonometry, constants |
random | Random numbers and choices |
datetime | Dates and times |
statistics | Mean, median and other statistics |
json | Converting between Python data and JSON text |
os and pathlib | Working with files and folders |
Libraries beyond the standard library
The tools that make Python the language of AI are not part of the standard library. They are published by the community and installed with a program called pip, which comes with Python.
On your own computer, you would type this in a terminal, not in a Python file:
pip install numpyThen you import the library like any other module. By convention, the big data libraries get standard nicknames.
import numpy as np
import pandas as pd
import matplotlib.pyplot as pltYour own modules
Any Python file you write is a module too. If you save some functions in a file called helpers.py, another file in the same folder can use them with import helpers. This is how large programs are split into manageable pieces.
Common mistakes
Import the math module and print the square root of 144.
# Use the math module to print the square root of 144. # Output must be exactly: 12.0
After writing import math , how do you call the sqrt function?
Summary
- A module is a file of reusable Python code.
import mathloads a module. Use its contents withmath.name.from math import sqrtimports a single name.import numpy as npgives a nickname.- The standard library comes with Python.
- Other libraries are installed with pip.
You now know every building block of the language. In the final module, you will put them together in two projects.
Finished reading? Tick it off to track your progress.