This is an archived version of the course. Please see the latest version of the course.

Python modules

Beyond the built-in functions and types, the Python Standard Library actually offers a large collection of modules and packages with lots of useful facilities.

You will have to explicitly import these modules or packages to use them, just like you would #include <iostream> in C++.

Let us try to import the math module to use it. To import a module, you just… well… import it!

>>> import math
>>> help(math)
>>> math.sqrt(9)
>>> math.log10(50)
>>> math.cos(30 * math.pi / 180)   # cosine of x radians

You can imagine a module as a Python script lying somewhere in your Python installation.

After you import math, you can access all the functions/variables/classes in that module via the dot (.) operator.

You may also rename your module when you import. In the example below, we renamed the math module to m to save us typing math all the time.

>>> import math as m
>>> m.sqrt(9)
>>> m.log10(50)
>>> m.cos(30 * m.pi / 180)   

You can also import only specific functions/variables/classes from math. Python will now have these functions/variables/classes directly in its namespace (list of identifiers that can currently be used), so you can now use them directly without having to refer to them via math.

>>> from math import sqrt, log10, cos, pi
>>> sqrt(9)
>>> log10(50)
>>> cos(30 * pi / 180)

Explore the Python Standard Library at your own pace. Some modules or packages (a hierarchy of modules) that you might find useful are math, collections, os, os.path and shutil.