Python supports modules or packages, these are code libraries or code bases that you can include in your program.

There are thousands of modules available, which will help you create all kinds of programs including network programs, desktop application and many more.

A module can be one or more Python files with one or more functions / variables. These functions and variables can be called from your program by importing a module.

Related course: Complete Python Programming Course & Exercises

Introduction

To load a module, all you have to do is include the import keyword on top of your Python program. You an import one or more modules in your Python program. For example to load the math module you can do

import math

The math module has many functions that are now available for use. These methods include sin(), cos() and many others. Modules often include variables too:

import math

print(math.pi)
x = math.sin(1)
print(x)

This principle holds true for all modules. You can import them and use their methods and variables.

Sometimes a module is not installed and you need to install a module.

Find functions and variables in module

If you want to find out which functions and variables exist in a Python module, there is a simple trick to do that.

To find the available functions in a module, you can use the dir(module) function call. This outputs all the available functions inside the module.

Lets try that for the math module:

import math

content = dir(math)
print(content)
A list will be returned with all functions and variables:

python module list all functions

You can use the Python interpreter to nicely format and quickly browse the number of available functions:

>>> import math
>>> for f in dir(math):
... print(f)

This then outputs all the functions and variables:

>>> for f in dir(math):
...     print(f)
... 
__doc__
__loader__
__name__
__package__
__spec__
acos
acosh
asin
asinh
atan
...

Related course: Complete Python Programming Course & Exercises

Create your own module

Besides existing modules, you can build your own modules that you can later use in many of your programs. So how do you create a module?

First create a Python file with a function. We call this file hello.py and we have one function def hello(). Of course a Python file can have many more functions, but for this example one is enough:

def hello():
print("Hello World")
Now that we have create a module named hello. Save it as hello.py and create a new file test.py. In the program test.py you can load the module using

import hello

Then you can access the function as if it were in the same file

hello.hello()

Instead of calling hello.hello() you can also import the function directly

from hello import hello

The contents of test.py:

 # Import your module
import hello

# Call of function defined in module
hello.hello()

Download exercises