Loading and using modules¶
What is a module?¶
A module in Python is simply a Python .py
file that contains a list of related functions that can be loaded and used.
Modules are similar to what are more generally called libraries in programming languages, which again contain code related to a specific task such as mathematical operations.
There are a HUGE number of Python modules, and many of them greatly extend what can be done in a normal Python console.
In fact, the abundance of free Python modules is one of the best reasons to learn and start using Python.
How can modules be loaded?¶
Python modules can be loaded in a number of different ways.
Let’s start simple with the
math
module. Here, we’ll load themath
module using theimport
statement.In [1]: import math In [2]: math.sqrt(81) Out[2]: 9.0
Here we have loaded the
math
module by typingimport math
, which tells Python to read in the functions in themath
module and make them available for use. In our example, we see that we can use a function within themath
library by typing the name of the module first, a period, and then the name of function we would like to use afterward (e.g.,math.sqrt()
). Built-in functions such asprint()
do not require the name of the module first since nothing is explicitly imported.
We can also rename modules when they are imported. This can be helpful when using modules with longer names.
In [3]: import math as m In [4]: m.sqrt(49) Out[4]: 7.0 In [5]: type(m)