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
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.
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.
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.
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.
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.
To see all functions in a module, start the Python interpreter and type
This will show all functions and classes in the module:
To make a module, create a Python file. Then import it like any other module.
Create your module (fruit.py)
Then create your program (example.py) and call the function:
If you get the error “ImportError: No module named
You can install a module with the pip package manager. To do so, it’s good to setup a virtualenv too.
Try the exercises below
- Import the math module and call the sin function
- Create your own module with the function snake()