A module is a file of Python code you can use from another file. import math loads the math module, and then math.sqrt(16) calls its sqrt function. from math import sqrt brings in just that name so you can write sqrt(16). import numpy as np gives a module a short nickname.
Python comes with hundreds of modules ready to use, called the standard library ("batteries included"). A few you'll use all the time:
import math
print(math.sqrt(81), math.pi > 3.14, math.ceil(4.1))
import random
roll = random.randint(1, 6)
print(1 <= roll <= 6)
coin = random.choice(["heads", "tails"])
print(coin in ("heads", "tails"))
Prints
9.0 True 5
True
True
random.randint(a, b) picks a whole number from a to b (both included), random.choice() picks an item, and random.shuffle() mixes a list. random.seed() makes the "random" sequence repeat, which helps when testing.
datetime handles dates and times, which are fiddlier than they look (months have different lengths, leap years, time zones). Subtracting two dates gives a timedelta, a length of time.
collections has handy containers. Counter counts things in one go, and defaultdict is a dict that makes a default value for a missing key, so grouping needs no get().
from collections import Counter, defaultdict
votes = ["tea", "coffee", "tea", "juice", "tea"]
print(Counter(votes).most_common(1))
by_letter = defaultdict(list)
for w in ["apple", "avocado", "banana"]:
by_letter[w[0]].append(w)
print(dict(by_letter))
Your own files are modules too. If helpers.py defines def tidy(s):, another file in the same folder can from helpers import tidy. Code at the top level of a module runs when it's imported, so scripts put their main work under if __name__ == "__main__":. That line is True only when the file is run directly, not when it's imported.
Beyond the standard library are hundreds of thousands of packages written by other people, on the Python Package Index (PyPI). You install them from the terminal with pip install requests, for example. The advanced course covers keeping each project's packages separate with a virtual environment.
Practice
What does this print?
import math
print(math.floor(7.9), math.ceil(7.1))
More info
Quick reference
import m / from m import x / import m as n
Load a module / one name from it / with a nickname.
math
sqrt, floor, ceil, pi and more.
random
randint(a, b), choice, shuffle, seed.
datetime
date, datetime, timedelta, strftime for formatting.
collections
Counter for counting, defaultdict for grouping.
if __name__ == "__main__":
Code that runs only when the file is run directly.