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 Programming Course & Exercises
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.
1 | import os |
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:
1 | 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.
1 | #!/usr/bin/python |
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.1
2
3#!/usr/bin/python
from time
time.sleep(2)
List functions in module
To see all functions in a module, start the Python interpreter and type1
2
3python
import os
dir(os)
This will show all functions and classes in the module:
Make a module
To make a module, create a Python file. Then import it like any other module.
Create your module (fruit.py)
1 | def lemon(): |
Then create your program (example.py) and call the function:
1 | import fruit |
python module not found
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.
1 | virtualenv projectname |
If you are a beginner, then I highly recommend this book.
Exercise
Try the exercises below
- Import the math module and call the sin function
- Create your own module with the function snake()