Online Courses

Modules example
Modules can be used to organize your code.  A module is a Python file with one or more functions and variables.  These functions and variables can be called from your program by importing a module.

A module may be used in your program. In this example we use the math module. This module has many functions such as sine, cosine as well as variables:

import math

x = math.sin(1)

Find available functions and variables in a Python module
To find the available functions in a module, you can use this code:

import math

content = dir(math)

A list will be returned with all functions and variables:

$ python
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 
'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 
'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 
'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

Create your own module
First create a Python file with a function. We call this file and we have one function:

def hello():
    print("Hello World")

Now that we have create a module named hello we can use it in our program

# Import your module
import hello

# Call of function defined in module
Write file
Date and Time

2 thoughts on “Modules

  1. Reply
    Abed Khateb - July 20, 2016

    “A list will be returned with all functions and functions:” should be functions and variables

    1. Reply
      admin - July 22, 2016

      Thanks! I’ve changed it

Leave a Reply

Your email address will not be published. Required fields are marked *