Modules and the Standard Library
A module is a file of ready-made code. Python comes with many useful ones. Bring them in with import.
Nobody writes everything from scratch. Python comes with a standard library - a large set of modules for maths, dates, random numbers, files, internet, and much more. Using them saves time, and they're well tested, so they have fewer bugs than code you'd write yourself.
import math brings in the whole module; you then write math.sqrt(). from datetime import date brings in just one part, so you can write date() directly. Both are common.
Dates
Dates are trickier than they look: months have different lengths, there are leap years, and formats differ between countries. The datetime module handles all of that. timedelta is a length of time you can add or subtract, like "4 days".
Random choices
The random module picks random values, so its output changes every time you run it:
import random
print(random.randint(1, 6)) # a dice roll
print(random.choice(["Red", "Blue"]))Installing more packages
Thousands of extra packages are on PyPI. Install them in a terminal with pip:
PyPI (the Python Package Index) is a free online store of packages written by people around the world. pip downloads and installs them. Popular ones: requests (talk to websites), pandas (data tables), flask (websites). Only install packages you trust - check they're popular and maintained.
pip install requestsshop.py, then use import shop in another file in the same folder.- Modules are files of ready-made code; bring them in with
import. - The standard library includes
math,datetime,randomand many more. - Install extra packages from PyPI with
pip install name.
