Skip to content
dreamcode
dreamcode
Map
Modules
Lesson 43 of 77
+15 XP on finish
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 math then math.sqrt(...): the module name keeps things organised
  • from collections import Counter brings 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__":.

main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Import math and use math.pi, rounding the area to two decimals. It should print 28.27.

Press Run to check your work.