Modules can have one or more functions. They help you to organize your code. Instead of one long Python file, you can have several files (modules).

A module is a Python file that has functions or classes. A Python program can use one or more modules.

Related course: Complete Python Bootcamp: Go from zero to hero in Python

Example

What is a module?

There are many modules (sometimes called libraries) available for Python. By using these modules you can code much faster.

Think of them like building blocks, they contain large sets of functions (sometimes classes) that provide you with additional functionality.

Import modules

You can load a module with the import keyword.

In the example below we load the os module. This is short for operating system, so you can do system tasks.

import os
os.system("dir")

Using that module we call one of its functions named system (runs a command).

In this case it will simply list the files in the directory (dir command).

There are many many modules available for Python.

Get specific functions from a module

To import a specific function in a module, you can use the line:

from module import function

There’s a module named time which has all kind of functionality for time: get the date, hour, minute, second and so on. That’s quite a lot of functionality.

Lets say you want the program to wait 2 seconds. If you want, you can import a specific function instead of the whole module.

#!/usr/bin/python
from time import sleep
sleep(2)

Import all functions from a module.

You can import all functions from a module, but this is not recommended.
The example below imports the whole time module (all functions), which you can then use.

#!/usr/bin/python
from time
time.sleep(2)

List functions in module

To see all functions in a module, start the Python interpreter and type

python
import os
dir(os)

This will show all functions and classes in the module:

module functions

Make a module

To make a module, create a Python file. Then import it like any other module.
Create your module (fruit.py)

def lemon():
print('Lemonade')

Then create your program (example.py) and call the function:

import fruit

fruit.lemon()

python module not found

If you get the error “ImportError: No module named“, this means the module is not installed.
You can install a module with the pip package manager. To do so, it’s good to setup a virtualenv too.

virtualenv projectname
cd projectname
source bin/activate
pip install module

Exercise

Try the exercises below

  1. Import the math module and call the sin function
  2. Create your own module with the function snake()

Download answers