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
mathmodule. Here, we’ll load the
mathmodule using the
In : import math In : math.sqrt(81) Out: 9.0
Here we have loaded the
mathmodule by typing
import math, which tells Python to read in the functions in the
mathmodule and make them available for use. In our example, we see that we can use a function within the
mathlibrary 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 as
print()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 : import math as m In : m.sqrt(49) Out: 7.0 In : type(m)