Modules in Python

After some time the code starts to get more complex, with lots of functions and variables.

To make it easier to organize the code we use Modules.

A well-designed Module also has the advantage to be reusable, so you write code once and reuse it everywhere.

You can write a module with all the mathematical operations and other people can use it.

And, if you need, you can use someone else’s modules to simplify your code, speeding up your project.

In other programming languages, these are also referred to as libraries.

Using a Module

To use a module we use the import keyword.

As the name implies we have to tell our program what module to import.

After that, we can use any function available in that module.

Let’s see an example using the math module.

First, let’s see how to have access to a constant, the Euler’s number.

import math

math.e
2.718281828459045

In this second example, we are going to use a function that calculates the square root of a number.

It is also possible to use the as keyword to create an alias.

import math as m

m.sqrt(121)

m.sqrt(729)
11
27

Finally, using the from keyword, we can specify exactly what to import instead of the whole module and use the function directly without the module’s name.

This example uses the floor() function that returns the largest integer less than or equal to a given number.

from math import floor

floor(9.8923)
9

Creating a Module

Now that we know how to use modules, let’s see how to create one.

It is going to be a module with the basic math operations add, subtract, multiply, divide and it is gonna be called basic_operations.

Create the basic_operations.py file with the four functions.

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    return a / b

Then, just import the basic_operations module and use the functions.

import basic_operations

basic_operations.add(10,2)
basic_operations.subtract(10,2)
basic_operations.multiply(10,2)
basic_operations.divide(10,2)
12
8
20
5.0