Skip to main content
`Ctrl`+`K`

# Library Code

Source code libraries contain reusable code. In Python reusing code written by other people is very simple and there are lots of code libraries available for free. Code libraries for Python are organized in modules and packages.

## Python Modules

Next to built-in functions like `print` and `input` Python ships with several modules, which can be loaded on demand. A module is a collection of additional functionality. Everybody can write and publish Python modules. How to do this will be explained later on. Modules either are written in Python or in some other laguage, mainly the C programming language.

Before we can use functionality of a module we have to import it:

    import numpy as np

Hint

A number of modules comes pre-installed with Python (the Python standard library). But many others have to be installed separately. Whenever Python shows `ModuleNotFoundError` you forgot to install the module you want to import. Install a module via Anaconda Navigator or with `conda install module_name` in a terminal, see Install Jupyter Locally project for more details.

The code above imports the module `numpy` and makes it accessible under the name `np`, which is shorter than ‘numpy’. NumPy is a collection of functions and data types for advanced numerical computations. We will dive deeper into this module later on. To use NumPy’s functionality we have to write `np.some_function` with `some_function` replaced by one of NumPy’s functions.

    np.sin(0.25 * np.pi)

    0.7071067811865475

Here, `np.pi` is a floating point variable holding an approximation of \(\pi\). The function `np.sin` computes the sine of its argument.

Note

The name `np` for accessing functionality of the module `numpy` can be choosen freely. But for widely used modules like NumPy there are standard names everybody should use to improve code readability. Names everybody should use are given in a module’s documentation (look at code examples there). Keep in mind: that’s a convention, `import numpy as wild_cat` would by okay, too, from the technical point of view.

## Python Packages

A package is a collection of modules. A module from a package can be imported via `import package.module`. A very important Python package is Matplotlib for scientific plotting:

    import matplotlib.pyplot as plt

    plt.plot([1, 2, 3, 4, 5], [20, 18, 10, 12, 18])
    plt.show()

With `plt.plot` we create a line plot and `plt.show` displays this plot. If the code runs in JupyterLab the plot is embedded into the notebook. If run by a plain Python interpreter a window opens showing the plot.

We will come back to Matplotlib when discussing data visualization.