PYTHON INTERMEDIATEChapter 7 · Errors, Files and Modules
Modules and imports
A module is a file of code you can reuse. Python ships with a large standard library: math for maths, random for chance, collections for handy containers, datetime for dates. import math gives you math.sqrt, from math import sqrt imports just that name, and import datetime as dt gives a module a shorter alias.
Worked example
How it reads
import maththenmath.sqrt(...): the module name keeps things organisedfrom collections import Counterbrings one name in directly- Subtracting two dates gives a
timedelta, a span of time

Cloud tip: Before writing a helper, check the standard library. Counting, dates, random choices and file paths are already solved.
Go deeper: Your own modules
Any .py file is a module. If helpers.py defines def greet():, another file in the same folder can import helpers and call helpers.greet().
Code at the top level of a module runs when it is imported. Guard code that should only run when the file is started directly with if __name__ == "__main__":.


